Bean 注册
注册Bean的常用注解有@Component、@Service、@Controller、@Repository,通过扫描包的方式对这些注解进行解析注册Bean。
注解ApplicationContext:AnnotationConfigApplicationContext
常用注解
@Configuration
声明Bean Difinition的配置文件,相当于一个xml文件
@Bean
声明Bean的组件
@Configuration
public class CustomConfig {
@Bean
public Person person() {
return new Person();
}
}
相当于xml bean内容
<beans>
<bean id="person" class="top.felixfly.entity.Person"/>
</beans>
bean的名称默认为方法名称,也可以通过@Bean(value=“person”)或者@Bean(“person”)进行指定
@ComponentScan
指定扫描路径
@Configuration
@ComponentScan("top.felixfly.spring.annotation")
public class ScanConfiguration {
}
相当于xml component-scan
<beans>
<context:component-scan package="top.felixfly.spring.annotation"/>
</beans>
@ComponentScans
多个扫描路径,值为ComponentScan的数组,1.8以后可以用多个@ComponentScan代替此注解
@Scope
指定Bean的作用域,默认为singleton
- singleton org.springframework.beans.factory.config.ConfigurableBeanFactory#SCOPE_SINGLETON
- prototype org.springframework.beans.factory.config.ConfigurableBeanFactory#SCOPE_PROTOTYPE
- request org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
- session org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
@Configuration
public class CustomConfig {
@Bean
@Scope("singleton")
public Person person() {
return new Person();
}
}
相当于xml中bean中scope属性
<beans>
<bean id="person" class="top.felixfly.entity.Person" scope="singleton"/>
</beans>
@Lazy
懒加载,针对singleton Bean进行懒加载,默认情况下单实例Bean直接加载
@Configuration
public class CustomConfig {
@Bean
@Lazy
public Person person() {
return new Person();
}
}
相当于xml中bean的lazy-init属性
<beans>
<bean id="person" class="top.felixfly.entity.Person" lazy-init="true"/>
</beans>
@DependsOn
依赖关系注解
@Configuration
public class CustomConfig {
@Bean
@DependsOn("person")
public Manager manager(){
return new Manager();
}
@Bean
public Person person(){
return new Person();
}
}
相当于xml中bean的depends-on属性
<beans>
<bean id="manager" class="top.felixfly.entity.Manager" depends-on="person"/>
</beans>
@Order
Bean的排序,或者说是优先级,两个接口org.springframework.core.Ordered以及org.springframework.core.Priori