@value获取不到值的问题


使用@Value的类,在spring中,不能直接通过new 操作符来使用,而是应该通过spring的注解 @Autowired 来使用

必须使用在bean的实例中,例如被@Controller,@Service,@Component等注解的类里边。

方法1

@Component
@Data
public class BootstrapInfo {
    @Value("${spring.profiles.active}")
    private String active;
    private static String profile;
    @PostConstruct
    public void setProfile() {
        profile = this.active;
    }
    public static String getProfile() {
        return profile;
    }
}

使用@Value获取yml配置文件的值。最后关键就是使用 @PostConstruct 熟悉将yml中配置的值赋给本地的变量,这样后面的静态方法就能使用了。

注意事项:
注意BootstrapInfo类使用了 @Component 属性注解了说明是需要在启动类 Application 启动的时候加载的,所以我们本地写一个方法调用 BootstrapInfo 的时候是获取不到 profile的。
 
 
 
 
 

方法2

public static Object getBootstrapYml(Object key){
        Resource resource = new ClassPathResource("bootstrap.yml");
        Properties properties = null;
        try {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties =  yamlFactory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return properties.get(key);
    }
 
    public static void main(String[] args) {
        System.out.println(getBootstrapYml("spring.profiles.active"));
    } 

yml和properties配置文件的获取方式可能会有所不同,要注意

 


转载参考:https://www.jianshu.com/p/3f9dfee94a04
 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM