習慣了用XML文件來配置spring,現在開始嘗試使用純java代碼來配置spring。
其實,spring的純java配置,簡單來說就是將bean標簽的內容通過注解轉換成bean對象的過程,沒什么神秘的地方。
首先來配置AppConfig文件:
配置的英文叫做configuration,所以,java配置文件的類前,為了說明此類屬於配置文件的范疇,就加上這樣一個標簽:@Configuration 用來標識此類是一個配置類;然后就是@ComponentScan 標簽,是不是很熟悉?對的,這個就是表示掃描范圍的一個標簽,后面可以加上一個屬性 basePackages 用來說明要管理的bean在哪個包下,使用方式和在XML文件里配置時的使用方法一樣,如果是多包掃面,就用大括號括起來,中間用逗號隔開就行了;其他的根據需要進行添加,譬如 @EnableScheduling 和 @EnableAspectJAutoProxy 等等,按需添加即可。
在這個文件里呢,我配置了一個數據庫。第一,通過@Autowired 來注入DataSource ,然后配置一個@Bean,就是寫一個datasource的實例就ok了。其他的,譬如shiro的配置等等都可以在這里進行,方法同data一樣。定義新攔截器也可在此處進行,需要說明的就是,攔截器的bean里需要添加一個name屬性,用來定義此攔截器的名稱,方便在web.xml中進行引用。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.util.FileCopyUtils; import javax.servlet.Filter; import javax.sql.DataSource; import java.io.FileReader; import java.io.IOException; @Configuration @EnableScheduling @EnableAspectJAutoProxy @ComponentScan(basePackages = {"com.lab.service", "com.lab.task", "com.lab.security"}) public class ApplicationConfig { @Autowired private DataSource dataSource; @Bean public IDBI database() { IDBI dbi = new DBI(dataSource); logger.debug("dbi : {}", dbi); return dbi; } // 。。。 }
其次就是配置WebConfig文件:
同前一個一樣,首先需要添加的就是@Configuration 標簽,還有一個不同的就是需要加上@EnableWebMvc 標簽以開啟MVC模式。當然也有@ComponentScan 標簽,使用方法同前,需要basePackages 屬性的定義。按需也可添加諸如 @EnableAspectJAutoProxy 等標簽。
這里定義的有譬如 setPrefix 和 setSuffix 等內容,具體按實際進行增減。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @EnableAspectJAutoProxy @ComponentScan(basePackages = { "com.lab.controller" }) public class WebConfig extends WebMvcConfigurerAdapter { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/view/"); resolver.setSuffix(".jsp"); return resolver; } }
定義DataConfig文件:
前面我是直接在AppConfig中進行注入了數據庫的定義,是因為具體的數據庫連接的定義我是在這里進行的。
@Configuration 必不可少了,然后我又定義了一個屬性 @Profile(“data”)用以說明此類的用途。然后就是定義了一個@Bean(name=“dataSource”) ,內容是數據庫連接池、鏈接的用戶名、密碼、等待超時時間啦等等一系列的數據庫的配置。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import com.alibaba.druid.pool.DruidDataSource; @Configuration @Profile("data") public class DevConfig {
/* 此處我用了properties文件的方式進行數據庫的定義,也可直接在代碼中書寫 */ private static final String databaseConfig = "datasource.properties"; @Bean(name = "dataSource") public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); InputStream inStream = null; try { Properties prop = new Properties(); inStream = getClass().getClassLoader().getResourceAsStream(databaseConfig); prop.load(inStream); String datastyle = prop.getProperty("data.style"); dataSource.setUrl( prop.getProperty(datastyle + ".data.url") + ":" + prop.getProperty(datastyle + ".data.database")); dataSource.setUsername(prop.getProperty(datastyle + ".data.user")); dataSource.setPassword(prop.getProperty(datastyle + ".data.password")); /* 配置過濾 */ dataSource.setFilters(prop.getProperty(datastyle + ".data.filters")); /* 配置初始化大小、最小、最大 */ dataSource.setInitialSize(Integer.parseInt(prop.getProperty(datastyle + ".data.initialSize"))); dataSource.setMinIdle(Integer.parseInt(prop.getProperty(datastyle + ".data.minIdle"))); dataSource.setMaxActive(Integer.parseInt(prop.getProperty(datastyle + ".data.maxActive"))); /* 配置獲取連接等待超時的時間 */ dataSource.setMaxWait(Integer.parseInt(prop.getProperty(datastyle + ".data.maxWait"))); /* 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 */ dataSource.setTimeBetweenEvictionRunsMillis( Integer.parseInt(prop.getProperty(datastyle + ".data.timeBetweenEvictionRunsMillis"))); /* 配置一個連接在池中最小生存的時間,單位是毫秒 */ dataSource.setMinEvictableIdleTimeMillis( Integer.parseInt(prop.getProperty(datastyle + ".data.minEvictableIdleTimeMillis"))); } catch (FileNotFoundException fileNotFoundException) { fileNotFoundException.printStackTrace(); } catch (IOException iOException) { iOException.printStackTrace(); } catch (SQLException sQLException) { sQLException.printStackTrace(); } return dataSource; } }
這些都定義好后,在web.xml文件中進行配置下就行了。
<!-- 上下文配置文件の地址 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> com.bell.lab.springconfig.DevConfig, com.bell.lab.springconfig.ApplicationConfig </param-value> </context-param>
<servlet> <servlet-name>SpringDemoServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextClass</param-name> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value>com.bell.lab.springconfig.WebConfig</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringDemoServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>data</param-value>
</context-param>
至此完事,跟在spring-application.xml中進行配置效果是一樣的,整體上更符合java的習慣而已。
ps:其實,就算是web.xml文件,也可通過java代碼的形式進行配置的,不過我覺着有點麻煩,就沒進行說明,感興趣的可以自行查找相關資料進行配置。