咱們以後可能用SpringBoot建立項目,可是裏面有些註解實際上是SpringFramework的,簡單講幾個java
此註解能夠替代配置文件,就是那個Spring的xml文件配置,也能夠理解成<beans>標籤數組
@Configuration public class AppConfig { }
//使用註解配置以後,實現類就不是ClassPathXmlApplicationContext而是AnnotationConfigApplicationContext //配置類自己也是組件,因此容器中會註冊此對象 ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class); 或者註解配置類的包路徑 ApplicationContext context=new AnnotationConfigApplicationContext("com.ty"); //查看容器裏面的組件 for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println(beanDefinitionName); }
建立對象,等同於配置文件中<bean>標籤測試
@Bean public User user(){ return new User(); } //測試 ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class); Object user = context.getBean("user"); System.out.println(user);
@Bean能夠指定id名字:@Bean("id")code
@Import還能夠搭配ImportSelector和ImportBeanDefinitionRegistrarcomponent
ps:在Spring5.2以後此註解搭配@Configuration使用時,@Configuration註解能夠添加proxyBeanMethods參數xml
默認值是true,用來檢查在容器中是否有這個組件對象
public class User { private Integer id; private String username; private Book book; /*getter/setter/toString/構造方法
public class Book { private String name; /*getter/setter/toString/構造方法
@Configuration(proxyBeanMethods = true) public class MyConfig { @Bean public User getUser() { User user = new User(18, "james"); //getUser組件依賴了getBook組件 user.setBook(getBook()); return user; } @Bean public Book getBook() { return new Book("三國"); } }
//測試 @Test public void test3() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); User user = (User) context.getBean("getUser"); Book userBook = user.getBook(); Book book = (Book) context.getBean("getBook"); System.out.println(userBook == book); //true }
說明:blog
當proxyBeanMethods = true時,表明Full模式,保證每一個@Bean方法被調用多少次返回的組件都是單實例的get
當proxyBeanMethods = false時,表明Lite模式,每一個@Bean方法被調用多少次返回的組件都是新建立的it
註解掃描,做用和配置文件中的<context:component-scan />標籤相同
@ComponentScan(basePackages = "com.ty.bean")
一樣跟配置文件同樣,能夠用過濾規則指定掃描包,即排除過濾和包含過濾
@ComponentScan(basePackages = "com.ty",excludeFilters = @ComponentScan.Filter(type = FilterType.ASPECTJ,pattern = "com.ty.bean.*"))
@ComponentScan(basePackages = "com.ty", useDefaultFilters = false, includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Repository.class))
過濾規則有多個的時候,能夠用大括號,好比:
@ComponentScan(basePackages = "com.ty.dao", useDefaultFilters = false, includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Repository.class, Service.class}), @ComponentScan.Filter(type = FilterType.ASPECTJ, pattern = "*..UserDaoImpl2")})
給容器中自動導入建立出所需的組件、默認組件的名字就是全類名
@Configuration @Import({Book.class, Log4jMDCAdapter.class}) public class AppConfig { }
條件裝配:知足Conditional指定的條件,則進行組件注入