Spring-IOC进阶注解
2021-03-08 17:30
标签:condition def 构造 clu 就是 port boot app oid 我们之后可能用SpringBoot创建项目,但是里面有些注解其实是SpringFramework的 此注解可以替代配置文件,就是那个Spring的xml文件配置,也可以理解成 创建对象,等同于配置文件中 @Bean可以指定id名字:@Bean("id") ps:在Spring5.2之后此注解搭配@Configuration使用时,@Configuration注解可以添加proxyBeanMethods参数 默认值是true,用来检查在容器中是否有这个组件 说明: 当proxyBeanMethods = true时,代表Full模式,保证每个@Bean方法被调用多少次返回的组件都是单实例的 当proxyBeanMethods = false时,代表Lite模式,每个@Bean方法被调用多少次返回的组件都是新创建的 注解扫描,作用和配置文件中的 同样跟配置文件一样,可以用过滤规则指定扫描包,即排除过滤和包含过滤 过滤规则有多个的时候,可以用大括号,比如: 给容器中自动导入创建出所需的组件、默认组件的名字就是全类名 条件装配:满足Conditional指定的条件,则进行组件注入 Spring-IOC进阶注解 标签:condition def 构造 clu 就是 port boot app oid 原文地址:https://www.cnblogs.com/hanyu-2020/p/14195112.html
@Configuration
@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);
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
}
@ComponentScan
@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
下一篇:java的read方法