使用@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的。
注意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