我们之后可能用SpringBoot创建项目,但是里面有些注解其实是SpringFramework的,简单讲几个
@Configuration
此注解可以替代配置文件,就是那个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>标签
@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")
@Import还可以搭配ImportSelector和ImportBeanDefinitionRegistrar
- ImportSelector:返回所需导入组件的全类名数组
- ImportBeanDefinitionRegistrar:手动注册到bean容器
ps:在Spring5.2之后此注解搭配@Configuration使用时,@Configuration注解可以添加proxyBeanMethods参数
默认值是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 }
说明:
当proxyBeanMethods = true时,代表Full模式,保证每个@Bean方法被调用多少次返回的组件都是单实例的
- 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式
当proxyBeanMethods = false时,代表Lite模式,每个@Bean方法被调用多少次返回的组件都是新创建的
- 配置类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
@ComponentScan
注解扫描,作用和配置文件中的<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")})
@Import
给容器中自动导入创建出所需的组件、默认组件的名字就是全类名
@Configuration @Import({Book.class, Log4jMDCAdapter.class}) public class AppConfig { }
@Conditional
条件装配:满足Conditional指定的条件,则进行组件注入