聊聊Spring中的各項注解
作者個人研發(fā)的在高并發(fā)場景下,提供的簡單、穩(wěn)定、可擴展的延遲消息隊列框架,具有精準(zhǔn)的定時任務(wù)和延遲隊列處理功能。自開源半年多以來,已成功為十幾家中小型企業(yè)提供了精準(zhǔn)定時調(diào)度方案,經(jīng)受住了生產(chǎn)環(huán)境的考驗。為使更多童鞋受益,現(xiàn)給出開源框架地址:https://github.com/sunshinelyz/mykit-delay
寫在前面
由于在更新其他專題的文章,Spring系列文章有很長一段時間沒有更新了,很多小伙伴都在公眾號后臺留言或者直接私信我微信催更Spring系列文章。
看來是要繼續(xù)更新Spring文章了。想來想去,寫一篇關(guān)于Spring中注解相關(guān)的文章吧,因為之前更新Spring系列的文章一直也是在更新Spring注解驅(qū)動開發(fā)。這篇文章也算是對之前文章的一個小小的總結(jié)吧,估計更新完這篇,我們會進入Spring的AOP章節(jié)的更新。
文章已收錄到:
https://github.com/sunshinelyz/technology-binghe
https://gitee.com/binghe001/technology-binghe
xml配置與類配置
1.xml配置
- <?xml version="1.0" encoding="UTF-8"?>
 - <beans xmlns="http://www.springframework.org/schema/beans"
 - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 - xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/sp
 - <bean id="person" class="com.binghe.spring.Person"></bean>
 - </beans>
 
獲取Person實例如下所示。
- public static void main( String[] args ){
 - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
 - System.out.println(ctx.getBean("person"));
 - }
 
2.類配置
- @Configuration
 - public class MainConfig {
 - @Bean
 - public Person person(){
 - return new Person();
 - }
 - }
 
這里,有一個需要注意的地方:通過@Bean的形式是使用的話, bean的默認(rèn)名稱是方法名,若@Bean(value="bean的名稱")那么bean的名稱是指定的 。
獲取Person實例如下所示。
- public static void main( String[] args ){
 - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
 - System.out.println(ctx.getBean("person"));
 - }
 
@CompentScan注解
我們可以使用@CompentScan注解來進行包掃描,如下所示。
- @Configuration
 - @ComponentScan(basePackages = {"com.binghe.spring"})
 - public class MainConfig {
 - }
 
excludeFilters 屬性
當(dāng)我們使用@CompentScan注解進行掃描時,可以使用@CompentScan注解的excludeFilters 屬性來排除某些類,如下所示。
- @Configuration
 - @ComponentScan(basePackages = {"com.binghe.spring"},excludeFilters = {
 - @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class}),
 - @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {PersonService.class})
 - })
 - public class MainConfig {
 - }
 
includeFilters屬性
當(dāng)我們使用@CompentScan注解進行掃描時,可以使用@CompentScan注解的includeFilters屬性將某些類包含進來。這里需要注意的是:需要把useDefaultFilters屬性設(shè)置為false(true表示掃描全部的)
- @Configuration
 - @ComponentScan(basePackages = {"com.binghe.spring"},includeFilters = {
 - @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, PersonService.class})
 - },useDefaultFilters = false)
 - public class MainConfig {
 - }
 
@ComponentScan.Filter type的類型
注解形式的FilterType.ANNOTATION @Controller @Service @Repository @Compent
- 指定類型的 FilterType.ASSIGNABLE_TYPE @ComponentScan.Filter(type =FilterType.ASSIGNABLE_TYPE,value = {Person.class})
 - aspectj類型的 FilterType.ASPECTJ(不常用)
 - 正則表達式的 FilterType.REGEX(不常用)
 - 自定義的 FilterType.CUSTOM
 
- public enum FilterType {
 - //注解形式 比如@Controller @Service @Repository @Compent
 - ANNOTATION,
 - //指定的類型
 - ASSIGNABLE_TYPE,
 - //aspectJ形式的
 - ASPECTJ,
 - //正則表達式的
 - REGEX,
 - //自定義的
 - CUSTOM
 - }
 
FilterType.CUSTOM 自定義類型
- public class CustomFilterType implements TypeFilter {
 - @Override
 - public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
 - //獲取當(dāng)前類的注解源信息
 - AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
 - //獲取當(dāng)前類的class的源信息
 - ClassMetadata classMetadata = metadataReader.getClassMetadata();
 - //獲取當(dāng)前類的資源信息
 - Resource resource = metadataReader.getResource();
 - return classMetadata.getClassName().contains("Service");
 - }
 - @ComponentScan(basePackages = {"com.binghe.spring"},includeFilters = {
 - @ComponentScan.Filter(type = FilterType.CUSTOM,value = CustomFilterType.class)
 - },useDefaultFilters = false)
 - public class MainConfig {
 - }
 
配置Bean的作用域?qū)ο?/strong>
不指定@Scope
在不指定@Scope的情況下,所有的bean都是單實例的bean,而且是餓漢加載(容器啟動實例就創(chuàng)建好了)
- @Bean
 - public Person person() {
 - return new Person();
 - }
 
@Scope為 prototype
指定@Scope為 prototype 表示為多實例的,而且還是懶漢模式加載(IOC容器啟動的時候,并不會創(chuàng)建對象,而是在第一次使用的時候才會創(chuàng)建)
- @Bean
 - @Scope(value = "prototype")
 - public Person person() {
 - return new Person();
 - }
 
@Scope取值
- singleton 單實例的(默認(rèn))
 - prototype 多實例的
 - request 同一次請求
 - session 同一個會話級別
 
懶加載
Bean的懶加載@Lazy(主要針對單實例的bean 容器啟動的時候,不創(chuàng)建對象,在第一次使用的時候才會創(chuàng)建該對象)
- @Bean
 - @Lazy
 - public Person person() {
 - return new Person();
 - }
 
@Conditional條件判斷
場景,有二個組件CustomAspect 和CustomLog ,我的CustomLog組件是依賴于CustomAspect的組件 應(yīng)用:自己創(chuàng)建一個CustomCondition的類 實現(xiàn)Condition接口
- public class CustomCondition implements Condition {
 - /****
 - @param context
 - * @param metadata
 - * @return
 - */
 - @Override
 - public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
 - //判斷容器中是否有CustomAspect的組件
 - return context.getBeanFactory().containsBean("customAspect");
 - }
 - }
 - public class MainConfig {
 - @Bean
 - public CustomAspect customAspect() {
 - return new CustomAspect();
 - }
 - @Bean
 - @Conditional(value = CustomCondition.class)
 - public CustomLog customLog() {
 - return new CustomLog();
 - }
 - }
 
向IOC 容器添加組件
(1)通過@CompentScan +@Controller @Service @Respository @compent。適用場景: 針對我們自己寫的組件可以通過該方式來進行加載到容器中。
(2)通過@Bean的方式來導(dǎo)入組件(適用于導(dǎo)入第三方組件的類)
(3)通過@Import來導(dǎo)入組件 (導(dǎo)入組件的id為全類名路徑)
- @Configuration
 - @Import(value = {Person.class})
 - public class MainConfig {
 - }
 
通過@Import 的ImportSeletor類實現(xiàn)組件的導(dǎo)入 (導(dǎo)入組件的id為全類名路徑)
- public class CustomImportSelector implements ImportSelector {
 - @Override
 - public String[] selectImports(AnnotationMetadata importingClassMetadata) {
 - return new String[]{"com.binghe.spring"};
 - }
 - }
 - Configuration
 - @Import(value = {Person.class}
 - public class MainConfig {
 - }
 
通過@Import的 ImportBeanDefinitionRegister導(dǎo)入組件 (可以指定bean的名稱)
- public class DogBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
 - @Override
 - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
 - //創(chuàng)建一個bean定義對象
 - RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Dog.class);
 - //把bean定義對象導(dǎo)入到容器中
 - registry.registerBeanDefinition("dog",rootBeanDefinition);
 - }
 - }
 - @Configuration
 - @Import(value = {Person.class, Car.class, CustomImportSelector.class, DogBeanDefinitionRegister.class})
 - public class MainConfig {
 - }
 
通過實現(xiàn)FacotryBean接口來實現(xiàn)注冊 組件
- public class CarFactoryBean implements FactoryBean<Car> {
 - @Override
 - public Car getObject() throws Exception {
 - return new Car();
 - }
 - @Override
 - public Class<?> getObjectType() {
 - return Car.class;
 - }
 - @Override
 - public boolean isSingleton() {
 - return true;
 - }
 - }
 
Bean的初始化與銷毀
指定bean的初始化方法和bean的銷毀方法
由容器管理Bean的生命周期,我們可以通過自己指定bean的初始化方法和bean的銷毀方法
- @Configuration
 - public class MainConfig {
 - //指定了bean的生命周期的初始化方法和銷毀方法.@Bean(initMethod = "init",destroyMethod = "destroy")
 - public Car car() {
 - return new Car();
 - }
 - }
 
針對單實例bean的話,容器啟動的時候,bean的對象就創(chuàng)建了,而且容器銷毀的時候,也會調(diào)用Bean的銷毀方法
針對多實例bean的話,容器啟動的時候,bean是不會被創(chuàng)建的而是在獲取bean的時候被創(chuàng)建,而且bean的銷毀不受IOC容器的管理
通過 InitializingBean和DisposableBean實現(xiàn)
通過 InitializingBean和DisposableBean個接口實現(xiàn)bean的初始化以及銷毀方法
- @Component
 - public class Person implements InitializingBean,DisposableBean {
 - public Person() {
 - System.out.println("Person的構(gòu)造方法");
 - }
 - @Override
 - public void destroy() throws Exception {
 - System.out.println("DisposableBean的destroy()方法 ");
 - }
 - @Override
 - public void afterPropertiesSet() throws Exception {
 - System.out.println("InitializingBean的 afterPropertiesSet方法");
 - }
 - }
 
通過JSR250規(guī)范
通過JSR250規(guī)范 提供的注解@PostConstruct 和@ProDestory標(biāo)注的方法
- @Component
 - public class Book {
 - public Book() {
 - System.out.println("book 的構(gòu)造方法");
 - }
 - @PostConstruct
 - public void init() {
 - System.out.println("book 的PostConstruct標(biāo)志的方法");
 - }
 - @PreDestroy
 - public void destory() {
 - System.out.println("book 的PreDestory標(biāo)注的方法");
 - }
 - }
 
通過BeanPostProcessor實現(xiàn)
通過Spring的BeanPostProcessor的 bean的后置處理器會攔截所有bean創(chuàng)建過程
- postProcessBeforeInitialization 在init方法之前調(diào)用
 - postProcessAfterInitialization 在init方法之后調(diào)用
 
- @Component
 - public class CustomBeanPostProcessor implements BeanPostProcessor {
 - @Override
 - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
 - System.out.println("CustomBeanPostProcessor...postProcessBeforeInitialization:"+beanName);
 - return bean;
 - }
 - @Override
 - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
 - System.out.println("CustomBeanPostProcessor...postProcessAfterInitialization:"+beanName);
 - return bean;
 - }
 - }
 
BeanPostProcessor的執(zhí)行時機
- populateBean(beanName, mbd, instanceWrapper)
 - initializeBean{
 - applyBeanPostProcessorsBeforeInitialization()
 - invokeInitMethods{
 - isInitializingBean.afterPropertiesSet()
 - 自定義的init方法
 - }
 - applyBeanPostProcessorsAfterInitialization()方法
 - }
 
通過@Value +@PropertySource來給組件賦值
- public class Person {
 - //通過普通的方式
 - @Value("獨孤")
 - private String firstName;
 - //spel方式來賦值
 - @Value("#{28-8}")
 - private Integer age;
 - 通過讀取外部配置文件的值
 - @Value("${person.lastName}")
 - private String lastName;
 - }
 - @Configuration
 - @PropertySource(value = {"classpath:person.properties"}) //指定外部文件的位置
 - public class MainConfig {
 - @Bean
 - public Person person() {
 - return new Person();
 - }
 - }
 
自動裝配
@AutoWired的使用
自動注入
- @Repository
 - public class CustomDao {
 - }
 - @Service
 - public class CustomService {
 - @Autowired
 - private CustomDao customDao;
 - }
 
結(jié)論: (1)自動裝配首先時按照類型進行裝配,若在IOC容器中發(fā)現(xiàn)了多個相同類型的組件,那么就按照 屬性名稱來進行裝配
- @Autowired
 - private CustomDao customDao;
 
比如,我容器中有二個CustomDao類型的組件 一個叫CustomDao 一個叫CustomDao2那么我們通過@AutoWired 來修飾的屬性名稱時CustomDao,那么拿就加載容器的CustomDao組件,若屬性名稱為tulignDao2 那么他就加載的時CustomDao2組件
(2)假設(shè)我們需要指定特定的組件來進行裝配,我們可以通過使用@Qualifier("CustomDao")來指定裝配的組件 或者在配置類上的@Bean加上@Primary注解
- @Autowired
 - @Qualifier("CustomDao")
 - private CustomDao customDao2
 
(3)假設(shè)我們?nèi)萜髦屑礇]有CustomDao 和CustomDao2,那么在裝配的時候就會拋出異常
- No qualifying bean of type 'com.binghhe.spring.dao.CustomDao' available
 
若我們想不拋異常 ,我們需要指定 required為false的時候可以了
- @Autowired(required = false)
 - @Qualifier("customDao")
 - private CustomDao CustomDao2;
 
(4)@Resource(JSR250規(guī)范) 功能和@AutoWired的功能差不多一樣,但是不支持@Primary 和@Qualifier的支持
(5)@InJect(JSR330規(guī)范) 需要導(dǎo)入jar包依賴,功能和支持@Primary功能 ,但是沒有Require=false的功能
- <dependency>
 - <groupId>javax.inject</groupId>
 - <artifactId>javax.inject</artifactId>
 - <version>1</version>
 - </dependency>
 
(6)使用@Autowired 可以標(biāo)注在方法上
- 標(biāo)注在set方法上
 
- //@Autowired
 - public void setCustomLog(CustomLog customLog) {
 - this.customLog = customLog;
 - }
 
- 標(biāo)注在構(gòu)造方法上
 
- @Autowired
 - public CustomAspect(CustomLog customLog) {
 - this.customLog = customLog;
 - }
 
標(biāo)注在配置類上的入?yún)⒅?可以不寫)
- @Bean
 - public CustomAspect CustomAspect(@Autowired CustomLog customLog) {
 - CustomAspect customAspect = new CustomAspect(customLog);
 - return ustomAspect;
 - }
 
XXXAwarce接口
我們自己的組件 需要使用spring ioc的底層組件的時候,比如 ApplicationContext等我們可以通過實現(xiàn)XXXAware接口來實現(xiàn)
- @Component
 - public class CustomCompent implements ApplicationContextAware,BeanNameAware {
 - private ApplicationContext applicationContext;
 - @Override
 - public void setBeanName(String name) {
 - System.out.println("current bean name is :【"+name+"】");
 - }
 - @Override
 - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
 - this.applicationContext = applicationContext;
 - }
 - }
 
@Profile注解
通過@Profile注解 來根據(jù)環(huán)境來激活標(biāo)識不同的Bean
@Profile標(biāo)識在類上,那么只有當(dāng)前環(huán)境匹配,整個配置類才會生效
@Profile標(biāo)識在Bean上 ,那么只有當(dāng)前環(huán)境的Bean才會被激活
沒有標(biāo)志為@Profile的bean 不管在什么環(huán)境都可以被激活
- @Configuration
 - @PropertySource(value = {"classpath:ds.properties"})
 - public class MainConfig implements EmbeddedValueResolverAware {
 - @Value("${ds.username}")
 - private String userName;
 - @Value("${ds.password}")
 - private String password;
 - private String jdbcUrl;
 - private String classDriver;
 - @Override
 - public void setEmbeddedValueResolver(StringValueResolver resolver) {
 - this.jdbcUrl = resolver.resolveStringValue("${ds.jdbcUrl}");
 - this.classDriver = resolver.resolveStringValue("${ds.classDriver}");
 - }
 - @Bean
 - @Profile(value = "test")
 - public DataSource testDs() {
 - return buliderDataSource(new DruidDataSource());
 - }
 - @Bean
 - @Profile(value = "dev")
 - public DataSource devDs() {
 - return buliderDataSource(new DruidDataSource());
 - }
 - @Bean
 - @Profile(value = "prod")
 - public DataSource prodDs() {
 - return buliderDataSource(new DruidDataSource());
 - }
 - private DataSource buliderDataSource(DruidDataSource dataSource) {
 - dataSource.setUsername(userName);
 - dataSource.setPassword(password);
 - dataSource.setDriverClassName(classDriver);
 - dataSource.setUrl(jdbcUrl);
 - return dataSource;
 - }
 - }
 
激活切換環(huán)境的方法
(1)運行時jvm參數(shù)來切換
- -Dspring.profiles.active=test|dev|prod
 
(2)通過代碼的方式來激活
- public static void main(String[] args) {
 - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
 - ctx.getEnvironment().setActiveProfiles("test","dev");
 - ctx.register(MainConfig.class);
 - ctx.refresh();
 - printBeanName(ctx);
 - }
 
本文轉(zhuǎn)載自微信公眾號「冰河技術(shù)」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系冰河技術(shù)公眾號。
















 
 
 












 
 
 
 