动态注入属性值(一)

一、在javaConfig中利用Environment注入属性值
1、普通的Student类

public class Student {
    private int age;
    private String name;

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

    public void display(){
        System.out.println("name:"+name+"  age:"+age);
    }
}

2、属性值文件 testvalue.properties

test.name=shazima
test.age=3232

3、JavaConfig配置文件

import org.springaction.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;


@Configuration
//声明属性源
@PropertySource("classpath:testvalue.properties")
public class StudentConfig {

    //注入environment
    @Autowired
    Environment env;

    @Bean
    public Student student(){
    //如果属性值key不存在,可以设置默认值,没有指定默认值,那获取值就是null;env.getProperty(String key[,String defaultValue])
    //实际age类型是int,而获取的类型是String,需要进行转换env.getProperty(String key,Integer.class[,int defaultValue])
    //获取的属性值必须要定义 env.getRequiredProperty()方法,如果没有定义则抛出异常
        return new Student(env.getProperty("test.age",Integer.class),env.getProperty("test.name")){};
    }
}

4、测试文件

@RunWith(SpringJUnit4ClassRunner.class)
//配置类
@ContextConfiguration(classes = StudentConfig.class)
public class CDPConfigTest {

    @Autowired
    private Student student;

    @Test
    public void doP(){
        student.display();
    }
}

二、利用属性占位符注入属性值
1、在JavaConfig中使用占位符

@Configuration
//声明属性源
@PropertySource("classpath:testvalue.properties")
public class StudentConfig {
//它能够基于Spring Environment及其属性源来解析占位符
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public Student student(
         @Value("${test.age}") int age,
         @Value("${test.name}") String name)
    {
        return new Student(age,name);
    }


}

2、在XML中通过属性占位符注入属性值
2.1、在XML中增加如下配置

<context:property-placeholder location="testvalue.properties"/>

    <bean id="student" class="org.springaction.Student"
          c:name="${test.name}"
          c:age="${test.age} "
          />
在 Spring 框架中实现 property 前缀注入,可以通过 `@ConfigurationProperties` 注解来完成,这是 Spring Boot 提供的种将具有相同前缀的配置项映射到一个 Java Bean 的机制。这种方式适用于需要多个配置属性构成一个对象的情况,相比 `@Value` 更适合处理结构化的配置信息 [^2]。 ### 使用 `@ConfigurationProperties` 实现前缀注入 首先,在 `application.properties` 或 `application.yml` 中定义组具有相同前缀的属性: ```properties my.config.key1=value1 my.config.key2=123 my.config.key3=true ``` 然后,创建一个 Java 类来接收这些配置: ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "my.config") public class MyConfigProperties { private String key1; private int key2; private boolean key3; // Getters and Setters } ``` 通过 `@ConfigurationProperties(prefix = "my.config")` 注解,Spring Boot 会自动将 `my.config` 前缀下的所有属性注入到对应的字段中 [^2]。 ### 配置启用 `@ConfigurationProperties` 为了使 `@ConfigurationProperties` 生效,需要在主配置类或启动类上添加 `@EnableConfigurationProperties` 注解: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; @SpringBootApplication @EnableConfigurationProperties(MyConfigProperties.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样,Spring 容器会自动识别并绑定 `MyConfigProperties` 类中的字段与配置文件中的 `my.config` 前缀属性 [^2]。 ### 使用 `@Value` 注入单个属性 如果只需要注入单个属性,可以使用 `@Value` 注解。它支持 SpEL 表达式和占位符方式注入值: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyComponent { @Value("${my.config.key1}") private String key1; @Value("#{T(java.lang.Math).random()}") private double randomValue; // 使用 key1 和 randomValue } ``` 这种方式适用于简单场景,例如只需要注入一个字符串、数字或布尔值的情况 [^1]。 ### 前缀注入的适用场景 - **结构化配置**:当配置项具有层级结构或多个相关属性时,使用 `@ConfigurationProperties` 更加清晰、易于维护 。 - **单个属性注入**:对于简单的属性注入,`@Value` 更加灵活,支持 SpEL 表达式和静态方法调用 [^3]。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值