02SpringBoot属性注入

Posted 小楼夜听雨QAQ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了02SpringBoot属性注入相关的知识,希望对你有一定的参考价值。

1、实现方式一:Spring中的@PropertySource

@Component
@PropertySource("classpath:user.properties")
public class UserInfo {
    @Value("${user.username}")
    private String username;

    @Value("${user.password}")
    private String password;

    @Value("${user.age}")
    private Integer age;

    @Override
    public String toString() {
        return "UserInfo{" +
                "username=‘" + username + ‘‘‘ +
                ", password=‘" + password + ‘‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

配置文件中:

user.username=‘admin‘
user.password=‘123‘
user.age=88

测试:

@SpringBootTest
public class UserInfoTest {
    @Autowired
    UserInfo userInfo;
    @Test
    public void user(){
        System.out.println(userInfo.toString());
    }
}

结果:

UserInfo{username=‘‘admin‘‘, password=‘‘123‘‘, age=88}

注意:此方法是不安全的,如果在配置文件中找不到对应的属性,例如没有username属性,会报错如下:

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userInfo‘: Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder ‘user.username‘ in value "${user.username}"

2、实现方式二:通过SpringBoot特有的@ConfigurationProperties来实现

注意点: 需要getter、setter函数

@Component
@PropertySource("classpath:user.properties")
@ConfigurationProperties(prefix = "user")
public class UserInfo {
//    @Value("${user.username}")
    private String username;

//    @Value("${user.password}")
    private String password;

//    @Value("${user.age}")
    private Integer age;


    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

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

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "username=‘" + username + ‘‘‘ +
                ", password=‘" + password + ‘‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

这种方法比较安全,即使配置文件中没有对于属性,也不会抛出异常。

以上是关于02SpringBoot属性注入的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot.02.SpringBoot创建对象与属性注入

SpringBoot.02.SpringBoot创建对象与属性注入

SpringBoot.02.SpringBoot创建对象与属性注入

02SpringBoot属性注入

3.springboot:springboot配置文件(配置文件YAML属性文件值注入<@Value@ConfigurationProperties@PropertySource,@Im(代码片

3springboot:springboot配置文件(配置文件YAML属性文件值注入<@Value@ConfigurationProperties@PropertySource,@Imp(代码片