Spring注解开发之@Bean和@ComponentScan
2021-04-01 00:27
标签:include def 修改 ica 测试的 lte component 告诉 time 搭建好maven web工程 pom加入spring-context,spring-core等核心依赖 创建实例类com.hjj.bean.Person, 生成getter,setter方法 创建com.hjj.config.MainConfig 主测试类 配置类中MainConfig.java 新建测试的com.hjj.controller,service,dao 单元测试 ComponentScan字段,有includeFilter(),和excludeFilter() 只包含或排除某些组件 @ComponentScan被@Repeatable(ComponentScans.class),可以重复写,用来写不同的执行策略。 @ComponentScans 里面可以放ComponentScan类型的值 Spring注解开发之@Bean和@ComponentScan 标签:include def 修改 ica 测试的 lte component 告诉 time 原文地址:https://www.cnblogs.com/jimmyhe/p/13549493.html组件注册
用@Bean来注册
public class Person {
private String name;
private int age;
}
@Configuration //告诉spring是一个配置类
public class MainConfig {
// 给容器中注册一个Bean,类行为返回值的类型,id默认是用方法名作为id
@Bean("mikePerson")
public Person person(){
return new Person("mike",20);
}
}
public class MainTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
for (String type : beanNamesForType) {
System.out.println(type); //配置类中的方法名,注意:通过修改配置类的@bean value也可以修改
}
}
}
@ComponentScan包扫描
@Configuration //告诉spring是一个配置类
@ComponentScan("com.hjj") // 扫描包的路径
public class MainConfig {
// 给容器中注册一个Bean,类行为返回值的类型,id默认是用方法名作为id
@Bean("mikePerson")
public Person person(){
return new Person("mike",20);
}
}
@Controller
public class BookController {
}
@Repository
public class BookDao {
}
@Service
public class BookService {
}
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); //获取所有组件
for (String beanDefinitionName : beanDefinitionNames) {
System.out.println(beanDefinitionName);
}
}
@ComponentScan(value = "com.hjj",excludeFilters={@Filter(type=FilterType.ANNOTATION,classes={Controller.class,Service.class})})
@ComponentScan(value = "com.hjj",includeFilters={@Filter(type=FilterType.ANNOTATION,classes={Controller.class,Service.class})},userDefaultFilters=false)
// excludeFilter源码
ComponentScan.Filter[] excludeFilters() default {};
// ComponentScan.Filter源码
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Filter {
FilterType type() default FilterType.ANNOTATION;
@AliasFor("classes")
Class>[] value() default {};
@AliasFor("value")
Class>[] classes() default {};
String[] pattern() default {};
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
public @interface ComponentScans {
ComponentScan[] value();
}
下一篇:什么是数组?
文章标题:Spring注解开发之@Bean和@ComponentScan
文章链接:http://soscw.com/index.php/essay/70689.html