裝配SpringBean(六)--配置文件加載方式


spring中的配置文件有兩種:

  • 以XML結尾的spring配置文件
  • 以properties結尾的屬性配置文件

在spring中有兩種方式加載這兩種文件:

  • 通過注解+java配置的方式
  • 通過XML的方式

詳細配置且看下文:

一、加載spring配置文件*.xml

假設有一個關於數據源的配置文件spring-database.xml,它的配置內容如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6         http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context
 8         http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 9 
10     <!-- 配置數據源 -->
11     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
12         <property name="driverClassName" value="org.postgresql.Driver" />
13         <property name="url" value="jdbc:postgresql://localhost:5433/postgres" />
14         <property name="username" value="postgres" />
15         <property name="password" value="postgres" />
16     </bean>
17 </beans>

1⃣️通過注解+java配置方式

第一步:通過注解+配置方式時需要創建一個配置類AppConfig.java

1 @ComponentScan(basePackages= {"com.hyc.config"}) 2 @ImportResource({"classpath:spring-database.xml"}) 3 public class AppConfig {
4 
5 }

上面的配置中:

1⃣️使用注解@ImportResource引入配置文件,可以是多個;

2⃣️通過注解@ComponentScan定義spring掃描的包(因為下面有個bean的類我定義在這個包下,所以這里加上這個掃描路徑)

第二步:寫一個獲取數據庫連接的類

 1 package com.hyc.config;  2 /*
 3  * 通過注解+配置的方式加載spring配置文件
 4  */
 5 
 6 import java.sql.Connection;
 7 import java.sql.SQLException;
 8 
 9 import javax.sql.DataSource;
10 
11 import org.springframework.beans.factory.annotation.Autowired;
12 import org.springframework.stereotype.Component;
13 
14 @Component("dbba") 15 public class DatasourceByAnnotation {
16 
17     @Autowired
18     DataSource dataSource = null;
19 
20     // 獲取數據庫連接
21     public Connection getConnection() {
22         Connection conn = null;
23         try {
24             conn = dataSource.getConnection();
25             if (null != conn) {
26                 System.out.println("獲取數據庫連接成功");
27             } else {
28                 System.out.println("獲取數據庫連接失敗");
29             }
30         } catch (SQLException e) {
31             e.printStackTrace();
32         }
33 
34         return conn;
35     }
36 }

上面代碼中加粗部分:

  • 此類所在的包,需要告知spring在哪個包下掃描,如果配置文件類和這個類在同意包下,則不需要配置
  • @Component注解:定義此bean的名稱,這樣可以通過getBean方法獲取到

第三步:編寫測試方法

1 public class GetDatasourceByConfigTest {
2 
3     @Test
4     public void testGetByConfig() {
5         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 6         DatasourceByAnnotation dba = (DatasourceByAnnotation) context.getBean("dbba");
7         dba.getConnection();
8     }
9 }

這里就是使用注解+java配置方式獲取bean,調用其方法,測試結果:

 配置成功,有些書上說這個地方獲取DataSource時可以使用自動注解,我試了一下是不可以的,其實按理說也是不行的,因為DataSource是第三方包中的類,我們無法對它進行修改,如果使用自動注解獲取,必定要給他增加@Component注解進行定義,所以這種方式只能通過配置獲取。

2⃣️通過XML方式

使用XML的方式,假設我要在spring-bean.xml中引入spring-database.xml文件,只需要在spring-bean.xml中加入一句代碼即可:

<import resource="spring-database.xml"/>

這樣就可以當作spring-bean.xml文件進行使用了,其實這種方式主要是為了將不同業務的配置通過文件區分開來,不要是spring-bean.xml文件變得很龐大復雜,具體實現不做介紹。 

二、加載屬性配置文件*.properties

依然是數據源的配置文件,只不過這次將其寫在屬性配置文件db.properties中,配置如下:

1 db.driver=org.postgresql.Driver
2 db.url=jdbc:postgresql://localhost:5433/postgres
3 db.username=postgresql
4 db.pwd=postgresql

1⃣️通過注解+java配置方式

第一步:通過注解+配置方式時需要創建一個配置類AppConfig.java

1 @Configuration 2 @PropertySource(value = { "classpath:db.properties" }, ignoreResourceNotFound = true) 3 public class AppConfig {
4 
5 }

上面的配置中:

  • 使用注解@PropertySource引入配置文件,可以是多個;
  • 通過注解@Configuration不能缺失,否則將找不到這個配置

第二步:測試

1 @Test
2     public void testGetPropByConfig() {
3         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
4         String url = context.getEnvironment().getProperty("db.url");
5         System.out.println(url);
6     }

獲取屬性文件中的數據庫連接URL,看能不能獲取到,測試結果如下:

可見獲取成功。

上面的測試中是通過環境來獲取對應的配置屬性,但如果這樣在spring中是沒有解析屬性占位符的能力,spring推薦使用一個屬性文件解析類PropertySourcePlaceholderConfigurer,使用它就意味允許spring解析對應的屬性文件,並通過占位符去引用對應的配置。

修改上述的配置類為如下:

 1 @Configuration
 2 @ComponentScan(basePackages = { "com.hyc.config" })
 3 @PropertySource(value = { "classpath:db.properties" }, ignoreResourceNotFound = true)
 4 public class AppConfig {
 5 
 6     /**
 7      * 定義一個PropertyPlaceholderConfigurer類的bean,它的作用是為了讓spring能解析占位符
 8      * @return
 9      */
10     @Bean
11     public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
12         return new PropertyPlaceholderConfigurer();
13     }
14 
15 }

有了上面的配置,就可以通過占位符引用屬性值了,如下:

 1 @Component("dsb")
 2 public class DataSourceBean {
 3 
 4     @Value("${db.driver}")
 5     private String driver = null;
 6 
 7     @Value("${db.url}")
 8     private String url = null;
 9 
10     @Value("${db.username}")
11     private String userName = null;
12 
13     @Value("${db.pwd}")
14     private String pwd = null;
15 
16     public void getDataSourceUrl() {
17         System.out.println(url);
18     }
19 
20 }

 

編寫測試類:

1 @Test
2     public void testGetPropByConfig1() {
3         @SuppressWarnings("resource")
4         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
5         DataSourceBean ds = (DataSourceBean) context.getBean("dsb");
6         ds.getDataSourceUrl();
7     }

這樣就能獲取到了

2⃣️通過XML方式

XML方式的配置如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6         http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context
 8         http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 9 
10     <!-- 配置單個屬性文件 -->
11     <context:property-placeholder
12         ignore-resource-not-found="false" location="classpath*:db.properties" />
13     <!-- 配置多個屬性文件 -->
14     <bean
15         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
16         <property name="locations">
17             <array>
18                 <value>classpath:db.properties</value>
19                 <value>classpath:log4j.properties</value>
20             </array>
21         </property>
22         <property name="ignoreResourceNotFound" value="false"></property>
23     </bean>
24 </beans>

 如上,可以配置多個,也可以配置一個,這樣以來,就能在spring的配置文件中通過占位符引用屬性了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM