SpringBoot(十八)@value、@Import、@ImportResource、@PropertySource
阿新 • • 發佈:2018-12-23
生效 boot.s titles toc 實例 @property auto private ber
Spring Boot提倡基於Java的配置。這兩篇博文主要介紹springboot 一些常用的註解介紹
v@value
通過@Value可以將外部的值動態註入到Bean中。
添加application.properties的屬性,方便後面演示。
domain.name=cnblogs
@Value("字符串1") private String testName; // 註入普通字符串 @Value("#{systemProperties[‘os.name‘]}") private String systemPropertiesName; //註入操作系統屬性 @Value("#{ T(java.lang.Math).random() * 100.0 }") private double randomNumber; //註入表達式結果 @Value("${domain.name}") private String domainName; // 註入application.properties的配置屬性
效果如下:
v@Import
SpringBoot 的 @Import 用於將指定的類實例註入之Spring IOC Container中。
package com.cnblogs.demo;public class Dog { }
package com.cnblogs.demo; public class Cat { }
在啟動類中需要獲取Dog和Cat對應的bean,需要用註解@Import註解把Dog和Cat的bean註入到當前容器中。
package com.cnblogs.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; //@SpringBootApplication @ComponentScan /*把用到的資源導入到當前容器中*/ @Import({Dog.class, Cat.class}) public class App { public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = SpringApplication.run(App.class, args); System.out.println(context.getBean(Dog.class)); System.out.println(context.getBean(Cat.class)); context.close(); } }
v@ImportResource
Spring Boot裏面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別;想讓Spring的配置文件生效,加載進來;@ImportResource標註在一個配置類上.
@ImportResource(locations = {"classpath:applicationContext.xml"}) @SpringBootApplication public class SpringBootConfigApplication { public static void main(String[] args) { SpringApplication.run(SpringBootConfigApplication.class, args); } }
v@PropertySource
自定義配置文件名稱,多用於配置文件與實體屬性映射。
person.properties
person.lastName=Jack
person.age=18
person.birth=2018/12/9
person.boss=true
person.maps.key1=value1
person.maps.key2=value2
person.lists=a,b,c
person.dog.name=tom
person.dog.age=1
@PropertySource(value = {"classpath:person.properties"}) @ConfigurationProperties(prefix = "person") @Component public class Person { private String lastName; private Integer age; private boolean isBoss; private Date birth; private Map<String, Object> maps; private List<Object> lists; private Dog dog; ...setter/getter/toString... }
SpringBoot(十八)@value、@Import、@ImportResource、@PropertySource