共计 2449 个字符,预计需要花费 7 分钟才能阅读完成。
一、定义
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {@AliasFor(annotation = Component.class)
String value() default "";}
@Configuration 的作用,指定一个或多个 @Bean 办法,由 spring 加载和生成 bean, 相当于 xml 的 root 标签。
二、例子
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {// instantiate, configure and return bean ...}
}
三、如何让 spring 加载它?
1、通过 ApplicationContext 加载
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
MyBean myBean = ctx.getBean(MyBean.class);
// use myBean ...
2、通过 xml 加载
<beans>
<context:annotation-config/>
<bean class="com.acme.AppConfig"/>
</beans>
3、通过 @ComponentScan
@ComponentScan("com.acme.app.services")
待加载的类放到扫描包外面
四、其它用法
1、@Component
- 被 @Configuration 注解的类也是一个 @Component
- @Autowired, @Value 都能用
@Configuration
public class AppConfig {
@Autowired Environment env;
@Value("${bean.name}") String beanName;
@Bean
public MyBean myBean() {MyBean myBean = new MyBean();
myBean.setName(env.getProperty("bean.name"));
return myBean;
}
}
2、搭配 Import
@Configuration
public class DatabaseConfig {
@Bean
public DataSource dataSource() {// instantiate, configure and return DataSource}
}
@Configuration
@Import(DatabaseConfig.class)
public class AppConfig {
private final DatabaseConfig dataConfig;
public AppConfig(DatabaseConfig dataConfig) {this.dataConfig = dataConfig;}
@Bean
public MyBean myBean() {// reference the dataSource() bean method
return new MyBean(dataConfig.dataSource());
}
}
3、搭配 Profile 辨别多环境
@Profile("development")
@Configuration
public class EmbeddedDatabaseConfig {
@Bean
public DataSource dataSource() {// instantiate, configure and return embedded DataSource}
}
@Profile("production")
@Configuration
public class ProductionDatabaseConfig {
@Bean
public DataSource dataSource() {// instantiate, configure and return production DataSource}
}
或者用这种
@Configuration
public class ProfileDatabaseConfig {@Bean("dataSource")
@Profile("development")
public DataSource embeddedDatabase() { ...}
@Bean("dataSource")
@Profile("production")
public DataSource productionDatabase() { ...}
}
4、加载 xml 外面的 bean
@Configuration
@ImportResource("classpath:/com/acme/database-config.xml")
public class AppConfig {
@Inject DataSource dataSource; // from XML
@Bean
public MyBean myBean() {
// inject the XML-defined dataSource bean
return new MyBean(this.dataSource);
}
}
5、多个嵌套应用
@Configuration
public class AppConfig {
@Inject DataSource dataSource;
@Bean
public MyBean myBean() {return new MyBean(dataSource);
}
@Configuration
static class DatabaseConfig {
@Bean
DataSource dataSource() {return new EmbeddedDatabaseBuilder().build();}
}
}
欢送关注微信公众号:丰极,更多技术学习分享。
正文完