Spring之属性赋值

124 阅读1分钟

27c372a9725d7b59.webp

在Spring中将配置文件中的值映射进java类中有几种不同的方式,以及自动装配的使用,欢迎一起来扫盲

属性赋值

  • 在以往中,我们在创建Bean的时候会在springapplicationContext.xml配置文件中声明一个,如果需要导入外部配置文件,还需要加载进来。类似这种:
<context:property-placeholder location="classpath:student.properties"/>
<bean id="student" class="com.xxx.Student" scope="prototype">
    <property name="age" value="${student.age}"></property>
    <property name="name" value="haha"></property>
</bean>
  • 现在我们通过注解方式加载Bean就要这么实现:
    • 在对应的Bean属性上加@value注解,注解中的值可以直接写
    • 1.基本数值,2.可以写SPEL #{},3.可以写${} 取出配置文件【properties】中的值
    • 取配置文件中的值那么就需要像xml那样的方式将配置文件读进来,就在配置类上加个@PorpertySource注解
//使用@ProrertySource 读取外部配置文件中的k/v保存进运行的环境变量中
@PropertySource(value={"classpath:/student.properties"})
@Configuration
public class MyConfig{}

//student类
public class Student{
    
    //直接赋值成张三
    @Value("张三")
    private String name;
    
    //计算
    @Value("#{20-2}")
    private Integer age;
    
    //从配置文件中取值
    @Value("${student.address}")
    private String address;
}

自动装配

  • @Autowired
    • 默认是按照类型去找对应的组件。假如类型有多个,再将属性的名称作为组件的id去容器中查找。
    • 也可以使用@Qualifierd注解显示的标明要注入组件的id
    • 也可以用@Primary注解声明首选的要注入的Bean
@Configuration
public class MyConfig{
    
    //加了@Primary注解,如果容器中存在相同的student类型的实例,首选这个
    @Primary
    @Bean("student")
    public Student student1(){
        return new Student(23, "张三");
    }
    
    @Bean("student")
    public Student student2(){
        return new Student(25, "李四");
    }
}
  • @Resource
    • 是java规范的注解,也可以和@Autowired一样实现自动装配功能,
    • 默认是按照组件名称进行装配。假如没有这个名字,按照类型去匹配,如果匹配多个则报错
    • 没有能支持@Primary功能,没有@Autowired(reqiured = false)功能

@Profile注解

  • 指定组件在哪个环境下才能注册到容器中,不指定,任何环境下都能注册这个组件
  • 加了环境标识的bean,只有这个环境被激活的时候才能注册到容器中,默认是default
public class MyConfig{
    //环境是test的时候,这个bean才加到容器中
    @Profile("test")
    @Bean
    public Student student(){
        Student student = new Student();
        student.setName("测试环境student");
        student.setAge(23);
        return student;
    }
}
  • 设置环境标识
    • 使用命令行动态参数:-Dspring.profiles.active=test
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    
    //创建一个applicationContext,设置激活的环境
    applicationContext.getEnvironment().setActiveProfiles("test");
    //注册主配置类
    applicationContext.register(MyConfig.class);
    //启动刷新容器
    applicationContext.refresh();

原始的spring 是不是感觉很美丽,直到后面的springboot 等技术通透之后在看看之前的原生spring 会别有一番感觉❤️