更新時間:2022-07-18 12:57:55 來源:動力節點 瀏覽1655次
1.通過context:property-placeholder加載配置文件jdbc.properties中的內容
<context:property-placeholder location="classpath:jdbc.properties"
ignore-unresolvable="true"/>
上面的配置和下面配置等價,是對下面配置的簡化:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- 配置組件掃描,springmvc容器中只掃描Controller注解 -->
<context:component-scan base-package="com.zxt.www" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
2.使用util:properties標簽進行暴露properties文件中的內容
<util:properties id="propertiesReader" location="classpath:jdbc.properties"/>
注意:使用上面這行配置,需要在spring-dao.xml文件的頭部聲明以下部分:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
\
3.通過PropertyPlaceholderConfigurer在加載上下文的時候暴露properties到自定義子類的屬性中以供程序中使用
<bean id="propertyConfigurer" class="com.hafiz.www.util.PropertyConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
自定義類 PropertyConfigurer 的聲明如下:
/**
* Desc:properties配置文件讀取類
*/
public class PropertyConfigurer extends PropertyPlaceholderConfigurer {
private Properties props; // 存取properties配置文件key-value結果
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
throws BeansException {
super.processProperties(beanFactoryToProcess, props);
this.props = props;
}
public String getProperty(String key){
return this.props.getProperty(key);
}
public String getProperty(String key, String defaultValue) {
return this.props.getProperty(key, defaultValue);
}
public Object setProperty(String key, String value) {
return this.props.setProperty(key, value);
}
}
使用方式:在需要使用的類中使用 @Autowired 注解注入即可。
4.自定義工具類PropertyUtil,并在該類的static靜態代碼塊中讀取properties文件內容保存在static屬性中以供別的程序使用
/**
* Desc:properties文件獲取工具類
*/
public class PropertyUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
private static Properties props;
static{
loadProps();
}
synchronized static private void loadProps(){
logger.info("開始加載properties文件內容.......");
props = new Properties();
InputStream in = null;
try {
<!--第一種,通過類加載器進行獲取properties文件流-->
in = PropertyUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
<!--第二種,通過類進行獲取properties文件流-->
//in = PropertyUtil.class.getResourceAsStream("/jdbc.properties");
props.load(in);
} catch (FileNotFoundException e) {
logger.error("jdbc.properties文件未找到");
} catch (IOException e) {
logger.error("出現IOException");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
logger.error("jdbc.properties文件流關閉出現異常");
}
}
logger.info("加載properties文件內容完成...........");
logger.info("properties文件內容:" + props);
}
public static String getProperty(String key){
if(null == props) {
loadProps();
}
return props.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
if(null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}
}
說明:這樣的話,在該類被加載的時候,它就會自動讀取指定位置的配置文件內容并保存到靜態屬性中,高效且方便,一次加載,可多次使用。
5.使用注解的方式注入,主要用在java代碼中使用注解注入properties文件中相應的value值
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<!-- 這里是PropertiesFactoryBean類,它也有個locations屬性,也是接收一個數組,跟上面一樣 -->
<property name="locations">
<array>
<value>classpath:jdbc.properties</value>
</array>
</property>
</bean>
6.@Value(常用)
application.properties 配置文件
string.port=1111
integer.port=1111
db.link.url=jdbc:mysql://localhost:3306/test
db.link.driver=com.mysql.jdbc.Driver
db.link.username=root
db.link.password=root
類文件:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyConf {
@Value("${string.port}") private int intPort;
@Value("${string.port}") private String stringPort;
@Value("${db.link.url}") private String dbUrl;
@Value("${db.link.driver}") private String dbDriver;
@Value("${db.link.username}")private String dbUsername;
@Value("${db.link.password}")private String dbPassword;
public void show(){
System.out.println("======================================");
System.out.println("intPort : " + (intPort + 1111));
System.out.println("stringPort : " + (stringPort + 1111));
System.out.println("string : " + dbUrl);
System.out.println("string : " + dbDriver);
System.out.println("string : " + dbUsername);
System.out.println("string : " + dbPassword);
System.out.println("======================================");
}
}
類名上指定配置文件@PropertySource可以聲明多個,或者使用@PropertySources(@PropertySource(“xxx”),@PropertySource(“xxx”))。
在bean中使用@value注解獲取配置文件的值
@Value("${key}")
private Boolean timerEnabled;
即使給變量賦了初值也會以配置文件的值為準。
7.import org.springframework.core.env.Environment;
(1)如何引用這個類:
可以通過 @Autowired注入Environment
@Autowired
private Environment environment;
可以通過實現 EnvironmentAware 然后實現接口中的方法
@Setter
private Environment environment;
(2)常用功能
獲取屬性配制文件中的值:environment.getProperty("rabbitmq.address")
獲取是否使用profile的
public boolean isDev(){
boolean devFlag = environment.acceptsProfiles("dev");
return devFlag;
}
8.@ConfigurationProperties(常用)
通過@ConfigurationProperties讀取配置信息并與 bean 綁定,可以像使用普通的 Spring bean 一樣,將其注入到類中使用。
@Component
@ConfigurationProperties(prefix = "library")
class LibraryProperties {
@NotEmpty
private String location;
private List<Book> books;
@Setter
@Getter
@ToString
static class Book {
String name;
String description;
}
//省略getter/setter
......
}
9.PropertySource(不常用)
@PropertySource 讀取指定 properties 文件
@Component
@PropertySource("classpath:website.properties")
class WebSite {
@Value("${url}")
private String url;
省略getter/setter
......
}
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習