咱们以后可能用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指定的条件,则进行组件注入