spring属性配置PropertySource、@Value、Environment、@ConfigurationProperties的用法

时间:2025-02-13 14:25:49

1、@PropertySource注解根据不同环境动态加载自定义配置文件

1.1、自定义配置文件

=zhangsan
=18
=man

1.2、pom里配置环境

<profile>
			<id>as-dev</id>
			<properties>
				<port>8081</port>
				<ctx>/dev</ctx>
				<env>as-dev</env>
			</properties>
			
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
		
		</profile>

1.3、里引用环境

=@env@
=@port@
-path=@ctx@

1.4、@PropertySource加载

@PropertySource("classpath:/common-${}.properties")
@Configuration
public class LoadProperties {

}

1.5、@Value注解引用

@Value("${}")
	private String stuName;

2、@value和Environment

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;


@RestController
/**
 * @RefreshScope
 * 要引入springcloud的config-server组件
 * 可以自定义注解,来实现等同于refreshScope注解等同的功能
 * @value注解动态刷新的关键是:@Scope注解的proxyMode属性,值默认为
 * 当@Scope中proxyMode为TARGET_CLASS的时候,会给当前创建的bean通过cglib生成一个代理对象,通过这个代理对象来访问目标bean对象
 * 当配置修改的时候,调用这些bean的任意方法的时候,就会重新创建一个代理对象
 */
@Scope
public class EnvTestController {

    /**
     * 可以将配置信息放在db或者其他存储介质中,容器启动的时候,可以将这些信息加载到Environment中,
     * @Value注解 中应用的值最终是通过Environment来解析的,所以只需要扩展一下Environment就可以实现
     */
    @Autowired
    private Environment env;

    @Value("${host:0.0.0.0}")
    private String host;
    @Value("${port:0}")
    private Integer port;

    {
        //在实例代码块里获取到的env变量一定是null,因为此时bean还没有初始化完成,无法注入env
        if(null == env){
            ("env为null");
        }
    }

    /**
     * 通过代码设置自定义的PropertySource,通过这种方式,@value不能刷新,而env则是能实时获取到值的
     */
    @RequestMapping("/customPropertySource/set")
    public void setCustomPropertySource(){
        StandardServletEnvironment ssEnv = null;
        if(env instanceof StandardServletEnvironment){
            ssEnv = (StandardServletEnvironment)env;
        }
        MutablePropertySources mutablePropertySources = ();
        Map<String, Object> map = new HashMap<>();
        ("host","192.168.32.1");
        ("port",8888);
        MapPropertySource mapPropertySource = new MapPropertySource("my_ps",map);
        (mapPropertySource);
    }

    @RequestMapping("/getProp/1/{key}")
    public String getProp1(@PathVariable String key){
        return (key);
    }

    @RequestMapping("/getProp/2/{key}")
    public String getProp2(@PathVariable String key){
        if("host".equals(key)){
            return host;
        }else if("port".equals(key)){
            return (port);
        }else{
            return null;
        }
    }

}

3、@ConfigurationProperties

3.1、用在类上

import ;
import ;
import ;
import ;

@Component
@PropertySource(value={"classpath:"},encoding="utf-8")
@ConfigurationProperties(prefix = "")
public class UserBean {
   private String name;
   private String age;
   private String email;

   public String getName() {
      return name;
   }

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

   public String getAge() {
      return age;
   }

   public void setAge(String age) {
       = age;
   }

   public String getEmail() {
      return email;
   }

   public void setEmail(String email) {
       = email;
   }
}

3.2、用在方法上

import ;
import ;
import ;
import ;
import ;
import ;

@Configuration
@PropertySource(value={"classpath:"},encoding="utf-8")
public class UserBeanConfig {

    @Bean
    @ConfigurationProperties(prefix = "")
    public User getUser(){
        return new User();
    }

}