Spring注解(一)——————Spring常用注解

关注微信公众号【行走在代码行的寻路人】获取Java相关资料,分享项目经验及知识干货。

以下测试的源码地址:https://github.com/877148107/Spring-Annotation

  • @Configuration

@Configuration:告诉Spring这是一个配置类,相当于原来的xml配置文件
  • @ComponentScan

@ComponentScan:指定要扫描的包,会把这个包下面注解的组件添加到容器中
  • @Import

@Import:快速给容器中导入一个组件,容器中就会自动注册这个组件,id默认是全类名

  • @MyImportSelector

@MyImportSelector:自定义逻辑返回需要导入的组件

  • @MyDefinitionRegistrar

@MyDefinitionRegistrar:自定义手动注册bean到容器中

@Configuration
@ComponentScan(value = {"com.spring.annotation.dao"})
@Import({annotationService.class, MyImportSelector.class, MyDefinitionRegistrar.class})
public class MyConfiguration {
    
}
public class MyImportSelector implements ImportSelector {

    /**
     * 这里返回时全类名的数组
     * @param annotationMetadata
     * @return
     */
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[]{"com.spring.annotation.bean.Cat"};
    }
}
public class MyDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
        boolean dog = registry.containsBeanDefinition("dog");
        if (!dog) {
            //指定bean
            RootBeanDefinition beanDefinition = new RootBeanDefinition(Dog.class);
            registry.registerBeanDefinition("dog",beanDefinition);
        }
    }
}
  •  @Bean

@Bean给容器中注册一个Bean,可以修改这个bean的名称
@Bean
    public Person person(){
        return new Person("张三",19);
    }
  • @Scope

@Scope:调整作用域
@Scope("prototype")prototype:多实例的:ioc容器启动并不会去调用方法创建对象放在容器中。
                              每次获取的时候才会调用方法创建对象;
@Scope("singleton")singleton:单实例的(默认值):ioc容器启动会调用方法创建对象放到ioc容器中。
                              以后每次获取就是直接从容器(map.get())中拿,
request:同一次请求创建一个实例
session:同一个session创建一个实例
    /**
     * @Scope:调整作用域
     * @Scope("prototype")prototype:多实例的:ioc容器启动并不会去调用方法创建对象放在容器中。
     *                                   每次获取的时候才会调用方法创建对象;
     * @Scope("singleton")singleton:单实例的(默认值):ioc容器启动会调用方法创建对象放到ioc容器中。
     *         			以后每次获取就是直接从容器(map.get())中拿,
     *        request:同一次请求创建一个实例
     *        session:同一个session创建一个实例
     * @return
     */
    @Scope
    @Bean
    public Person person(){
        return new Person("张三",19);
    }
  • @Conditional

@Conditional:满足条件就将给容器中注册bean
   /**
     * *@Conditional:满足条件就将给容器中注册bean
     * @return
     */
    @Conditional(MyConditional.class)
    @Bean
    public Color color(){
        return new Color();
    }

 

public class MyConditional implements Condition {

    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        Environment environment = conditionContext.getEnvironment();
        String property = environment.getProperty("os.name");
        if(property.contains("Windows")){
            return true;
        }
        return false;
    }
}
  • @Value

给对应的属性赋值

  • @PropertySource

加载外部配置文件

@PropertySource(value = {"classpath:/springboot.properties"})
@Configuration
public class MyPropertyValuesConfiguration {

    @Bean
    public Person person(){
        return new Person();
    }
}


public class Person {

    /**
     * 基本数值
     */
    @Value("李四")
    private String name;

    /**
     * 可以写SpEL; #{}
     */
    @Value("#{18-1}")
    private int age;

    /**
     * 可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)
     */
    @Value("${person.birthday}")
    private String birthday;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday='" + birthday + '\'' +
                '}';
    }
}


person.birthday=2020.10.10
  • @Controller

一般标注在controller层

  • @Service

一般标注在Service层

  • @Repository

一般标注在Dao层

  • @Autowired

自动注入,默认优先按照类型去容器中找对应的组件applicationContext.getBean(AnnotationDao.class)找到就赋值;如果找到多个相同类型的组件,再将属性的名称作为组件的id去容器中查找applicationContext.getBean("annotationDao")

AutowiredAnnotationBeanPostProcessor:解析完成自动装配功能

@Autowired:构造器,参数,方法,属性;都是从容器中获取参数组件的值
         1)、[标注在方法位置]:@Bean+方法参数;参数从容器中获取;默认不写@Autowired效果是一样的;都能自动装配
         2)、[标在构造器上]:如果组件只有一个有参构造器,这个有参构造器的@Autowired可以省略,参数位置的组件还是可以自动从容器中获取
         3)、放在参数位置:

  • @Qualifier

使用@Qualifier指定需要装配的组件的id,而不是使用属性名;自动装配默认一定要将属性赋值好,没有就会报错。可以使用可以使用@Autowired(required=false)就不会报错

  • @Primary

让Spring进行自动装配的时候,默认使用首选的bean;标注在注入bean的头上

@PropertySource(value = {"classpath:/springboot.properties"})
@Configuration
public class MyPropertyValuesConfiguration {

    @Primary
    @Bean
    public Person person(){
        return new Person();
    }
}
  • 使用Spring底层的组件自定义组件

实现xxxxAware接口即可,总的接口是Aware:在创建对象的时候会调用接口规定的方法注入相关组件。

xxxAware都会有一个xxxProcessor后置处理器

/**
 * @ClassName: Color
 * =================================================
 * @Description: 实现ApplicationContextAware:获取传入的IOC容器
 *               实现BeanNameAware:获取对应的beanname值
 * =================================================
 * CreateInfo:
 * @Author: William.Wangmy
 * @CreateDate: 2019/11/20 23:14        
 * @Version: V1.0
 *     
 */
@Component
public class Color implements ApplicationContextAware, BeanNameAware {

    private ApplicationContext applicationContext;

    public void color(){
        System.out.println("color 构造方法");
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("传入的IOC容器。。。。。。。。。。。");
        this.applicationContext = applicationContext;
    }

    public void setBeanName(String name) {
        System.out.println("bean,name:"+name);
    }
}
  •  @Profile

Spring为我们提供的可以根据当前环境,动态的激活和切换一系列组件的功能

/**
 * @ClassName: MyProfileConfiguration
 * =================================================
 * @Description: Profile:Spring为我们提供的可以根据当前环境,动态的激活和切换一系列组件的功能
 *               指定组件在哪个环境的情况下才能被注册到容器中,不指定,任何环境下都能注册
 * 1)、加了环境标识的bean,只有这个环境被激活的时候才能注册到容器中。默认是default环境
 * 2)、写在配置类上,只有是指定的环境的时候,整个配置类里面的所有配置才能开始生效
 * 3)、没有标注环境标识的bean在,任何环境下都是加载的;
 * 激活环节方法:1.在启动的环境变量中配置-Dspring.profiles.active=red(启动的环境名)
 *            2.在代码中激活
 *              //使用无参构造器创建一个容器
 *              AnnotationConfigApplicationContext applicationContext1 = new AnnotationConfigApplicationContext();
 *              //设置需要激活的环境
 *              applicationContext1.getEnvironment().setActiveProfiles("red","yellow");
 *              //注册主配置类
 *              applicationContext1.register(MyProfileConfiguration.class);
 *              //刷新启动器
 *              applicationContext1.refresh();
 *           3.写在配置类上,只有是指定的环境的时候,整个配置类里面的所有配置才能开始生效
 *
 * =================================================
 * CreateInfo:
 * @Author: William.Wangmy
 * @CreateDate: 2019/11/24 21:45
 * @Version: V1.0
 */
@Profile("blue")
@Configuration
public class MyProfileConfiguration {

//    @Profile("default")
    @Profile("blue")
    @Bean
    public Color blueColor(){
        return new Color("Bule");
    }

    @Profile("red")
    @Bean
    public Color redColor(){
        return new  Color("Red");
    }

    @Profile("yellow")
    @Bean
    public Color yellowColor(){
        return new Color("Yellow");
    }
}
  •  @Aspect

@Aspect表示注解的类为切面类,详细说明及使用见:https://blog.csdn.net/WMY1230/article/details/103230681

  • @EnableAspectJAutoProxy

开启基于注解的AOP模式。在Spring中还有许多@Enablexxxx开启某一项功能。​​​​​​​详细说明及使用见:https://blog.csdn.net/WMY1230/article/details/103230681

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值