首页 > 其他 > 详细

@Value注解和@PropertySource 注解的使用说明

时间:2021-06-06 21:27:52      阅读:25      评论:0      收藏:0      [点我收藏+]

1、作用和说明

  • @Value 相当于原来配置文件中的 value属性  <property name="age" value="20"/>
  • @PropertySource 相当于原来配置文件中的  <context:property-placeholder location="classpath:/person.properties"></context:property-placeholder> 这个标签,把属性 会放到环境变量中 Environment

2、代码说明

/**
 *
 * @PropertySource 这个注解会把 文件里面的k,v 放到环境变量中也即是  Environment
 *  <context:property-placeholder location="classpath:/person.properties"></context:property-placeholder>
 *
 *
 */

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


    @Bean
    public User getUer(){
        return new User();
    }
}

public class User {

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

    @Value("31")
    private int age;

    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 "User{" +
                "name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}



@Controller
public class Mycontroller {


    @Autowired
    Environment environment;


    @RequestMapping("/h1")
    public String hello(){

        System.out.println("evnvironment 中的 user.name is "+environment.getProperty("user.name1"));


        return "hello";
    }
}

 

@Value注解和@PropertySource 注解的使用说明

原文:https://www.cnblogs.com/gaohq/p/14856105.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!