ToB企服应用市场:ToB评测及商务社交产业平台

标题: Spring-常用注解及作用 [打印本页]

作者: 千千梦丶琪    时间: 2022-8-9 14:44
标题: Spring-常用注解及作用
@
目录

1.常用注解及作用

1.1 @Configuration

声明当前类是一个配置类(相当于一个Spring配置的xml文件)
1.2 @ComponentScan

自动扫描指定包下所有使用@Service,@Component,@Controller,@Repository的类并注册
示例:
  1. @ComponentScan(value="com.atguigu",includeFilters = {
  2.                 @Filter(type=FilterType.ANNOTATION,classes={Controller.class}),
  3.                 @Filter(type=FilterType.ASSIGNABLE_TYPE,classes={BookService.class}),
  4.                 @Filter(type=FilterType.CUSTOM,classes={MyTypeFilter.class})
  5.                         },useDefaultFilters = false)       
  6. //excludeFilters = Filter[] :指定扫描的时候按照什么规则排除那些组件
  7. //includeFilters = Filter[] :指定扫描的时候只需要包含哪些组件,
  8. 需设置useDefaultFilters = false
  9. //FilterType.ANNOTATION:按照注解
  10. //FilterType.ASSIGNABLE_TYPE:按照给定的类型;
  11. //FilterType.ASPECTJ:使用ASPECTJ表达式
  12. //FilterType.REGEX:使用正则指定
  13. //FilterType.CUSTOM:使用自定义规则
复制代码
1.3 @ComponentScans

可包含多个@ComponentScan
示例:@ComponentScans(value = {@ComponentScan,@ComponentScan,@ComponentScan})
1.4 @Lazy

单实例bean:默认在容器启动的时候创建对象;
懒加载:容器启动不创建对象。第一次使用(获取)Bean创建对象,并初始化;
1.5 @Conditional({Condition})

示例:@Conditional({WindowsCondition.class}),WindowsCondition是实现了Condition接口的类
按照一定的条件进行判断,满足条件给容器中注册bean,可定义在类名或者方法名上
1.6 注入组件

容器中注入组件的方式
1 @Bean:导入第三方的类或包的组件
2.ComponentScan:包扫描+组件的标注注解
3.@Import
4.使用Spring提供的FactoryBean(工厂Bean)进行注册
1.6.1 @Import()快速导入组件

可导入单个组件或者多个组件,id默认为全类名
示例:@Import(value={Dog.class,Cat.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class})
1.6.2.使用ImportSelector自定义需要导入的组件

ImportSelector是一个接口,接口定义的方法为一个包含组件全类名的字符串数组
  1. //自定义逻辑返回需要导入的组件
  2. public class MyImportSelector implements ImportSelector {
  3.         //返回值,就是到导入到容器中的组件全类名
  4.         //AnnotationMetadata:当前标注@Import注解的类的所有注解信息
  5.         @Override
  6.         public String[] selectImports(AnnotationMetadata importingClassMetadata) {
  7.                 // TODO Auto-generated method stub
  8.                 //importingClassMetadata
  9.                 //方法不要返回null值,否则会报空指针异常
  10.                 return new String[]{"com.bernard.bean.Blue","com.bernard.bean.Yellow"};
  11.         }
  12. }
复制代码
1.6.3.使用ImportBeamDefinitionRegistrar返回自定义组件
  1.     public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
  2.         /**
  3.          * AnnotationMetadata:当前类的注解信息
  4.          * BeanDefinitionRegistry:BeanDefinition注册类;
  5.          * 把所有需要添加到容器中的bean;
  6.          * 调用BeanDefinitionRegistry.registerBeanDefinition手工注册进来
  7.          */
  8.         @Override
  9.         public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
  10.                
  11.                 boolean definition = registry.containsBeanDefinition("com.atguigu.bean.Red");
  12.                 boolean definition2 = registry.containsBeanDefinition("com.atguigu.bean.Blue");
  13.                 if(definition && definition2){
  14.                         //指定Bean定义信息;(Bean的类型,Bean。。。)
  15.                         RootBeanDefinition beanDefinition = new RootBeanDefinition(RainBow.class);
  16.                         //注册一个Bean,指定bean名
  17.                         registry.registerBeanDefinition("rainBow", beanDefinition);
  18.                 }
  19.         }
  20. }
复制代码
测试类
打印出所有注册到容器的bean
  1. public class MyImportTest {
  2.     @Test
  3.     public void test01(){
  4.         AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MyImportConfig.class);
  5.         String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
  6.         for (int i = 0; i < beanDefinitionNames.length; i++) {
  7.             String beanDefinitionName = beanDefinitionNames[i];
  8.             System.out.println(beanDefinitionName);
  9.         }
  10.     }
  11. }
复制代码
1.6.4.使用Spring提供的 FactoryBean(工厂Bean);

1)、默认获取到的是工厂bean调用getObject创建的对象
2)、要获取工厂Bean本身,我们需要给id前面加一个&,如:“&colorFactoryBean”
  1. //创建一个Spring定义的FactoryBean
  2. public class ColorFactoryBean implements FactoryBean<Color> {
  3.         //返回一个Color对象,这个对象会添加到容器中
  4.         @Override
  5.         public Color getObject() throws Exception {
  6.                 // TODO Auto-generated method stub
  7.                 System.out.println("ColorFactoryBean...getObject...");
  8.                 return new Color();
  9.         }
  10.         @Override
  11.         public Class<?> getObjectType() {
  12.                 // TODO Auto-generated method stub
  13.                 return Color.class;
  14.         }
  15.         //是单例?
  16.         //true:这个bean是单实例,在容器中保存一份
  17.         //false:多实例,每次获取都会创建一个新的bean;
  18.         @Override
  19.         public boolean isSingleton() {
  20.                 // TODO Auto-generated method stub
  21.                 return false;
  22.         }
  23. }
复制代码
注册示例:
  1. @Bean
  2. public ColorFactoryBean colorFactoryBean(){
  3.         return new ColorFactoryBean();
  4. }
复制代码
获取示例
  1. //工厂Bean获取的是调用getObject创建的对象
  2. Object bean2 = applicationContext.getBean("colorFactoryBean");//获取getObject返回的bean
  3. Object bean4 = applicationContext.getBean("&colorFactoryBean");//获取工厂bean本身
复制代码
1.7 @Value

使用@Value可以为属性字段赋值
1、基本数值
2、可以写SpEL; #{}
3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)
配置类
使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;
加载完外部的配置文件以后使用${}取出配置文件的值
  1. @PropertySource(value={"classpath:/person.properties"})
  2. @Configuration
  3. public class MainConfigOfPropertyValues {
  4.        
  5.         @Bean
  6.         public Person person(){
  7.                 return new Person();
  8.         }
  9. }
复制代码
bean
  1. public class Person {
  2.         @Value("张三")
  3.         private String name;
  4.         @Value("#{20-2}")
  5.         private Integer age;
  6.        
  7.         @Value("${person.nickName}")
  8.         private String nickName;
  9. }
复制代码
1.8 @Autowired、@Resource、@Primary

@Autowired:构造器,参数,方法,属性;都是从容器中获取参数组件的值
补充:
@Autowired:Spring定义的;
@Resource、@Inject都是java规范

1.9 @Profile

指定组件在哪个环境的情况下才能被注册到容器中,不指定,任何环境下都能注册这个组件
  1. @PropertySource("classpath:/dbconfig.properties")
  2. @Configuration
  3. public class MainConfigOfProfile implements EmbeddedValueResolverAware{
  4.        
  5.         @Value("${db.user}")
  6.         private String user;
  7.        
  8.         private StringValueResolver valueResolver;
  9.        
  10.         private String  driverClass;
  11.        
  12.         @Bean
  13.         public Yellow yellow(){
  14.                 return new Yellow();
  15.         }
  16.        
  17.         @Profile("test")
  18.         @Bean("testDataSource")
  19.         public DataSource dataSourceTest(@Value("${db.password}")String pwd) throws Exception{
  20.                 ComboPooledDataSource dataSource = new ComboPooledDataSource();
  21.                 dataSource.setUser(user);
  22.                 dataSource.setPassword(pwd);
  23.                 dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
  24.                 dataSource.setDriverClass(driverClass);
  25.                 return dataSource;
  26.         }
  27.        
  28.         @Profile("dev")
  29.         @Bean("devDataSource")
  30.         public DataSource dataSourceDev(@Value("${db.password}")String pwd) throws Exception{
  31.                 ComboPooledDataSource dataSource = new ComboPooledDataSource();
  32.                 dataSource.setUser(user);
  33.                 dataSource.setPassword(pwd);
  34.                 dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_crud");
  35.                 dataSource.setDriverClass(driverClass);
  36.                 return dataSource;
  37.         }
  38.        
  39.         @Profile("prod")
  40.         @Bean("prodDataSource")
  41.         public DataSource dataSourceProd(@Value("${db.password}")String pwd) throws Exception{
  42.                 ComboPooledDataSource dataSource = new ComboPooledDataSource();
  43.                 dataSource.setUser(user);
  44.                 dataSource.setPassword(pwd);
  45.                 dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/scw_0515");
  46.                
  47.                 dataSource.setDriverClass(driverClass);
  48.                 return dataSource;
  49.         }
  50.         @Override
  51.         public void setEmbeddedValueResolver(StringValueResolver resolver) {
  52.                 // TODO Auto-generated method stub
  53.                 this.valueResolver = resolver;
  54.                 driverClass = valueResolver.resolveStringValue("${db.driverClass}");
  55.         }
  56. }
复制代码
激活方式:
激活测试代码
  1. public void test01(){
  2.         AnnotationConfigApplicationContext applicationContext =
  3.                         new AnnotationConfigApplicationContext();
  4.         //1、创建一个applicationContext
  5.         //2、设置需要激活的环境
  6.         applicationContext.getEnvironment().setActiveProfiles("dev");
  7.         //3、注册主配置类
  8.         applicationContext.register(MainConfigOfProfile.class);
  9.         //4、启动刷新容器
  10.         applicationContext.refresh();
  11.         String[] namesForType = applicationContext.getBeanNamesForType(DataSource.class);
  12.         for (String string : namesForType) {
  13.                 System.out.println(string);
  14.         }
  15.         Yellow bean = applicationContext.getBean(Yellow.class);
  16.         System.out.println(bean);
  17.         applicationContext.close();
  18. }
复制代码
1.10 @Scope

在注册bean时,spring默认是单实例的,即scope="singleton",除此之外,常见的scope还有prototype、request、session作用域
更多好文,欢迎点击:小C的博客

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4