下面列出了怎么用org.springframework.context.annotation.Configuration的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* SocketIOServer配置
*
* @param
* @return com.corundumstudio.socketio.SocketIOServer
* @author wliduo[[email protected]]
* @date 2019/4/17 11:41
*/
@Bean("socketIOServer")
public SocketIOServer socketIOServer() {
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
// 配置端口
config.setPort(port);
// 开启Socket端口复用
com.corundumstudio.socketio.SocketConfig socketConfig = new com.corundumstudio.socketio.SocketConfig();
socketConfig.setReuseAddress(true);
config.setSocketConfig(socketConfig);
// 连接数大小
config.setWorkerThreads(workCount);
// 允许客户请求
config.setAllowCustomRequests(allowCustomRequests);
// 协议升级超时时间(毫秒),默认10秒,HTTP握手升级为ws协议超时时间
config.setUpgradeTimeout(upgradeTimeout);
// Ping消息超时时间(毫秒),默认60秒,这个时间间隔内没有接收到心跳消息就会发送超时事件
config.setPingTimeout(pingTimeout);
// Ping消息间隔(毫秒),默认25秒。客户端向服务器发送一条心跳消息间隔
config.setPingInterval(pingInterval);
// 设置HTTP交互最大内容长度
config.setMaxHttpContentLength(maxHttpContentLength);
// 设置最大每帧处理数据的长度,防止他人利用大数据来攻击服务器
config.setMaxFramePayloadLength(maxFramePayloadLength);
return new SocketIOServer(config);
}
/**
* 根据配置文件选择机房
*/
@Bean
public com.qiniu.storage.Configuration qiniuConfig() {
Zone zone = null;
if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_BEI)) {
zone = Zone.huabei();
} else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_DONG)) {
zone = Zone.huadong();
} else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_NAN)) {
zone = Zone.huanan();
} else if (Objects.equals(qiniu.getZone(), QiniuZone.BEI_MEI)) {
zone = Zone.beimei();
} else if (Objects.equals(qiniu.getZone(), QiniuZone.XIN_JIA_PO)) {
zone = Zone.xinjiapo();
}
return new com.qiniu.storage.Configuration(zone);
}
@Bean
public SocketIOServer server(WsConfig wsConfig) {
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
config.setHostname(wsConfig.getHost());
config.setPort(wsConfig.getPort());
//这个listener可以用来进行身份验证
config.setAuthorizationListener(data -> {
// http://localhost:8081?token=xxxxxxx
// 例如果使用上面的链接进行connect,可以使用如下代码获取用户密码信息,本文不做身份验证
String token = data.getSingleUrlParam("token");
// 校验token的合法性,实际业务需要校验token是否过期等等,参考 spring-boot-demo-rbac-security 里的 JwtUtil
// 如果认证不通过会返回一个 Socket.EVENT_CONNECT_ERROR 事件
return StrUtil.isNotBlank(token);
});
return new SocketIOServer(config);
}
@Bean
public freemarker.template.Configuration freemarkConfig() {
/* ------------------------------------------------------------------------ */
/* You should do this ONLY ONCE in the whole application life-cycle: */
/* Create and adjust the configuration singleton */
freemarker.template.Configuration cfg = new freemarker.template.Configuration(
freemarker.template.Configuration.VERSION_2_3_22);
File folder;
try {
folder = ResourceUtils.getFile("classpath:templates");
cfg.setDirectoryForTemplateLoading(folder);
} catch (IOException e) {
e.printStackTrace();
}
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
return cfg;
}
@Bean
public HdfsFactory hdfsFactory() {
org.apache.hadoop.conf.Configuration configuration = new org.apache.hadoop.conf.Configuration();
configuration.addResource(new Path(properties.getCoreSiteXmlPath()));
configuration.addResource(new Path(properties.getHdfsSiteXmlPath()));
if (properties.getAuth().isEnabled()) {
System.setProperty("java.security.krb5.conf", properties.getAuth().getKrb5Conf());
System.setProperty("java.security.auth.login.config", properties.getAuth().getAuthLoginConfig());
UserGroupInformation.setConfiguration(configuration);
try {
UserGroupInformation.loginUserFromKeytab(properties.getAuth().getPrincipal(),
properties.getAuth().getAuthKeyTabPath());
} catch (IOException e) {
e.printStackTrace();
}
}
return new HdfsFactory(configuration);
}
@Bean
@ConditionalOnMissingBean
public cn.mybatisboost.core.Configuration configuration()
throws IllegalAccessException, InstantiationException {
cn.mybatisboost.core.Configuration.Builder builder =
cn.mybatisboost.core.Configuration.builder()
.setMultipleDatasource(properties.isMultipleDatasource())
.setIterateSelectiveInBatch(properties.isIterateSelectiveInBatch())
.setShowQuery(properties.isShowQuery())
.setShowQueryWithParameters(properties.isShowQueryWithParameters())
.setSlowQueryThresholdInMillis(properties.getSlowQueryThresholdInMillis());
if (properties.getNameAdaptor() != null) {
builder.setNameAdaptor(properties.getNameAdaptor().newInstance());
} else {
builder.setNameAdaptor(new NoopNameAdaptor());
}
if (properties.getSlowQueryHandler() != null) {
builder.setSlowQueryHandler(properties.getSlowQueryHandler().newInstance());
}
return builder.build();
}
@Bean
@ConditionalOnMissingBean
public DispatcherInterceptor mybatisBoostInterceptor(cn.mybatisboost.core.Configuration configuration) {
DispatcherInterceptor dispatcherInterceptor = new DispatcherInterceptor(configuration);
dispatcherInterceptor.appendPreprocessor(new MybatisCacheRemovingPreprocessor());
dispatcherInterceptor.appendPreprocessor(new ParameterNormalizationPreprocessor());
dispatcherInterceptor.appendPreprocessor(new AutoParameterMappingPreprocessor());
dispatcherInterceptor.appendProvider(new GeneratingSqlProvider());
if (isMapperEnabled) {
dispatcherInterceptor.appendProvider(new MapperSqlProvider(configuration));
}
if (isLangEnabled) {
dispatcherInterceptor.appendProvider(new LanguageSqlProvider(configuration));
}
if (isLimiterEnabled) {
dispatcherInterceptor.appendProvider(new LimiterSqlProvider(configuration));
}
return dispatcherInterceptor;
}
private char[] getLdapManagerPassword() {
char[] ldapPassword = null;
try {
String credentialProviderPath = logSearchSslConfig.getCredentialStoreProviderPath();
String ldapPasswordEnv = "LOGSEARCH_LDAP_MANAGER_PASSWORD";
if (StringUtils.isNotBlank(credentialProviderPath)) {
org.apache.hadoop.conf.Configuration config = new org.apache.hadoop.conf.Configuration();
config.set(LogSearchSslConfig.CREDENTIAL_STORE_PROVIDER_PATH, credentialProviderPath);
ldapPassword = config.getPassword("logsearch.auth.ldap.manager.password");
} else if (StringUtils.isNotBlank(authPropsConfig.getLdapAuthConfig().getLdapManagerPasswordFile())){
ldapPassword = FileUtils.readFileToString(new File(
authPropsConfig.getLdapAuthConfig().getLdapManagerPasswordFile()), Charset.defaultCharset()).toCharArray();
} else if (StringUtils.isNotBlank(System.getenv(ldapPasswordEnv))) {
ldapPassword = System.getenv(ldapPasswordEnv).toCharArray();
} else if (StringUtils.isNotBlank(authPropsConfig.getLdapAuthConfig().getLdapManagerPassword())) {
ldapPassword = authPropsConfig.getLdapAuthConfig().getLdapManagerPassword().toCharArray();
}
} catch (Exception e) {
logger.warn("Error during ldap password initialization. LDAP authentication probably won't work if a manager password will be required.", e);
}
return ldapPassword;
}
@Bean
public SocketIOServer server(WsConfig wsConfig) {
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
config.setHostname(wsConfig.getHost());
config.setPort(wsConfig.getPort());
//这个listener可以用来进行身份验证
config.setAuthorizationListener(data -> {
// http://localhost:8081?token=xxxxxxx
// 例如果使用上面的链接进行connect,可以使用如下代码获取用户密码信息,本文不做身份验证
String token = data.getSingleUrlParam("token");
// 校验token的合法性,实际业务需要校验token是否过期等等,参考 spring-boot-demo-rbac-security 里的 JwtUtil
// 如果认证不通过会返回一个 Socket.EVENT_CONNECT_ERROR 事件
return StrUtil.isNotBlank(token);
});
return new SocketIOServer(config);
}
/**
* 多数据源的 SqlSessionFactory
* @param dynamicDataSource
* @return
* @throws Exception
*/
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dynamicDataSource);
//设置数据数据源的Mapper.xml路径
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
//设置Mybaties查询数据自动以驼峰式命名进行设值
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session
.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
bean.setConfiguration(configuration);
return bean.getObject();
}
@Override
public boolean matches(Class<?> factory, Class<?> type) {
AnnotationMetadata metadata = getMetadata(factory);
Set<MethodMetadata> assignable = new HashSet<>();
for (MethodMetadata method : metadata.getAnnotatedMethods(Bean.class.getName())) {
Class<?> candidate = ClassUtils.resolveClassName(method.getReturnTypeName(), this.classLoader);
// Look for exact match first
if (type.equals(candidate)) {
return !this.evaluator.shouldSkip(method);
}
if (type.isAssignableFrom(candidate)) {
assignable.add(method);
}
}
if (assignable.size() == 1) {
return !this.evaluator.shouldSkip(assignable.iterator().next());
}
// TODO: fail if size() > 1
Class<?> base = factory.getSuperclass();
if (AnnotationUtils.isAnnotationDeclaredLocally(Configuration.class, base)) {
return matches(base, type);
}
return false;
}
@Bean
public SocketIOServer socketIOServer() {
/*
* 创建Socket,并设置监听端口
*/
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
// 设置主机名,默认是0.0.0.0
// config.setHostname("localhost");
// 设置监听端口
config.setPort(myProperties.getSocketPort());
// 协议升级超时时间(毫秒),默认10000。HTTP握手升级为ws协议超时时间
config.setUpgradeTimeout(10000);
// Ping消息间隔(毫秒),默认25000。客户端向服务器发送一条心跳消息间隔
config.setPingInterval(myProperties.getPingInterval());
// Ping消息超时时间(毫秒),默认60000,这个时间间隔内没有接收到心跳消息就会发送超时事件
config.setPingTimeout(myProperties.getPingTimeout());
// 握手协议参数使用JWT的Token认证方案
config.setAuthorizationListener(data -> {
// 可以使用如下代码获取用户密码信息
String token = data.getSingleUrlParam("token");
return true;
});
return new SocketIOServer(config);
}
@Bean
public SocketIOServer socketIOServer() {
/*
* 创建Socket,并设置监听端口
*/
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
// 设置主机名,默认是0.0.0.0
// config.setHostname("localhost");
// 设置监听端口
config.setPort(myProperties.getSocketPort());
// 协议升级超时时间(毫秒),默认10000。HTTP握手升级为ws协议超时时间
config.setUpgradeTimeout(10000);
// Ping消息间隔(毫秒),默认25000。客户端向服务器发送一条心跳消息间隔
config.setPingInterval(myProperties.getPingInterval());
// Ping消息超时时间(毫秒),默认60000,这个时间间隔内没有接收到心跳消息就会发送超时事件
config.setPingTimeout(myProperties.getPingTimeout());
return new SocketIOServer(config);
}
/**
* Configuring freemarker template file path.
*
* @return new FreeMarkerConfigurer
*/
@Bean
public FreeMarkerConfigurer freemarkerConfig(HaloProperties haloProperties) throws IOException, TemplateException {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPaths(FILE_PROTOCOL + haloProperties.getWorkDir() + "templates/", "classpath:/templates/");
configurer.setDefaultEncoding("UTF-8");
Properties properties = new Properties();
properties.setProperty("auto_import", "/common/macro/common_macro.ftl as common,/common/macro/global_macro.ftl as global");
configurer.setFreemarkerSettings(properties);
// Predefine configuration
freemarker.template.Configuration configuration = configurer.createConfiguration();
configuration.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
if (haloProperties.isProductionEnv()) {
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
// Set predefined freemarker configuration
configurer.setConfiguration(configuration);
return configurer;
}
@Bean("flinkEnvironment")
StreamExecutionEnvironment getFlinkEnvironment(FlinkProperties flinkProperties) {
long maxBytes = flinkProperties.getMaxClientRestRequestSizeBytes();
org.apache.flink.configuration.Configuration config = new org.apache.flink.configuration.Configuration();
config.setString("rest.address", flinkProperties.getJobManagerUrl());
config.setInteger("rest.port", flinkProperties.getJobManagerPort());
config.setLong("rest.client.max-content-length", maxBytes);
config.setLong("rest.server.max-content-length", maxBytes);
config.setString("akka.framesize", maxBytes + "b");
return StreamExecutionEnvironment.createRemoteEnvironment(
flinkProperties.getJobManagerUrl(),
flinkProperties.getJobManagerPort(),
config,
flinkProperties.getRemoteEnvJarFiles().stream().toArray(String[]::new));
}
private org.ehcache.config.Configuration createConfig(final ClassLoader cl) {
ResourcePoolsBuilder pools = ResourcePoolsBuilder.newResourcePoolsBuilder()
.heap(1000L, EntryUnit.ENTRIES);
// If needed, but will need to register serializers for the objects being stored
// .offheap(10L, MemoryUnit.MB)
// .disk(20, MemoryUnit.MB, false);
DefaultCacheEventListenerConfiguration cacheLogging = new DefaultCacheEventListenerConfiguration(EnumSet.allOf(EventType.class), CacheLogger.class);
return ConfigurationBuilder.newConfigurationBuilder()
.withService(new DefaultPersistenceConfiguration(SettingsService.getAirsonicHome().resolve("cache").toFile()))
.withCache("userCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Object.class, pools)
.withClassLoader(cl)
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofDays(2)))
.withService(cacheLogging))
.withCache("userSettingsCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Object.class, pools)
.withClassLoader(cl)
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofDays(2)))
.withService(cacheLogging))
.withCache("mediaFileMemoryCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Path.class, Object.class, pools)
.withClassLoader(cl)
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(10)))
.withService(cacheLogging))
.withCache("playlistCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Object.class, pools)
.withClassLoader(cl)
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofDays(10)))
.withService(cacheLogging))
.withCache("playlistUsersCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Object.class, pools)
.withClassLoader(cl)
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofDays(10)))
.withService(cacheLogging))
.build();
}
@Test
public void testBeanNamesForAnnotation() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(StandardConfig.class);
assertArrayEquals(new String[] {"beanMethodQualificationTests.StandardConfig"},
ctx.getBeanNamesForAnnotation(Configuration.class));
assertArrayEquals(new String[] {}, ctx.getBeanNamesForAnnotation(Scope.class));
assertArrayEquals(new String[] {"testBean1"}, ctx.getBeanNamesForAnnotation(Lazy.class));
assertArrayEquals(new String[] {"testBean2"}, ctx.getBeanNamesForAnnotation(Boring.class));
}
@Test
public void autowireMetadataIsPropagated() {
@Configuration class Config {
@Bean(autowire=Autowire.BY_TYPE) Object foo() { return null; }
}
assertEquals("autowire mode was not propagated",
AbstractBeanDefinition.AUTOWIRE_BY_TYPE, beanDef(Config.class).getAutowireMode());
}
@Test
public void autowireCandidateMetadataIsPropagated() {
@Configuration class Config {
@Bean(autowireCandidate=false) Object foo() { return null; }
}
assertFalse("autowire candidate flag was not propagated",
beanDef(Config.class).isAutowireCandidate());
}
@Test
public void initMethodMetadataIsPropagated() {
@Configuration class Config {
@Bean(initMethod="start") Object foo() { return null; }
}
assertEquals("init method name was not propagated",
"start", beanDef(Config.class).getInitMethodName());
}
@Test
public void destroyMethodMetadataIsPropagated() {
@Configuration class Config {
@Bean(destroyMethod="destroy") Object foo() { return null; }
}
assertEquals("destroy method name was not propagated",
"destroy", beanDef(Config.class).getDestroyMethodName());
}
@Test
public void dependsOnMetadataIsPropagated() {
@Configuration class Config {
@Bean() @DependsOn({"bar", "baz"}) Object foo() { return null; }
}
assertArrayEquals("dependsOn metadata was not propagated",
new String[] {"bar", "baz"}, beanDef(Config.class).getDependsOn());
}
@Test
public void primaryMetadataIsPropagated() {
@Configuration class Config {
@Primary @Bean
Object foo() { return null; }
}
assertTrue("primary metadata was not propagated",
beanDef(Config.class).isPrimary());
}
@Test
public void primaryMetadataIsFalseByDefault() {
@Configuration class Config {
@Bean Object foo() { return null; }
}
assertFalse("@Bean methods should be non-primary by default",
beanDef(Config.class).isPrimary());
}
@Test
public void lazyMetadataIsPropagated() {
@Configuration class Config {
@Lazy @Bean
Object foo() { return null; }
}
assertTrue("lazy metadata was not propagated",
beanDef(Config.class).isLazyInit());
}
@Test
public void lazyMetadataIsFalseByDefault() {
@Configuration class Config {
@Bean Object foo() { return null; }
}
assertFalse("@Bean methods should be non-lazy by default",
beanDef(Config.class).isLazyInit());
}
@Test
public void defaultLazyConfigurationPropagatesToIndividualBeans() {
@Lazy @Configuration class Config {
@Bean Object foo() { return null; }
}
assertTrue("@Bean methods declared in a @Lazy @Configuration should be lazily instantiated",
beanDef(Config.class).isLazyInit());
}
@Test
public void eagerBeanOverridesDefaultLazyConfiguration() {
@Lazy @Configuration class Config {
@Lazy(false) @Bean Object foo() { return null; }
}
assertFalse("@Lazy(false) @Bean methods declared in a @Lazy @Configuration should be eagerly instantiated",
beanDef(Config.class).isLazyInit());
}
@Test
public void eagerConfigurationProducesEagerBeanDefinitions() {
@Lazy(false) @Configuration class Config { // will probably never happen, doesn't make much sense
@Bean Object foo() { return null; }
}
assertFalse("@Lazy(false) @Configuration should produce eager bean definitions",
beanDef(Config.class).isLazyInit());
}
@Bean
public freemarker.template.Configuration dynamicConfig() {
freemarker.template.Configuration configuration =
new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_25);
configuration.setDateTimeFormat("UTF-8");
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
configuration.setClassicCompatible(true);
configuration.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
configuration.setTemplateLoader(new StringTemplateLoader());
return configuration;
}