SpringIoC和DI註解開發
文章目錄
1.Spring配置數據源
1.1 數據源(連接池)的作用
數據源(連接池)是提高程序性能如出現的
事先實例化數據源,初始化部分連接資源
使用連接資源時從數據源中獲取
使用完畢後將連接資源歸還給數據源
常見的數據源(連接池):DBCP、C3P0、BoneCP、Druid等
之前 我們是自定義的Bean
我想一個東西產生一系列的Bean 給我們使用
數據源 連接池 是提高程序性能出現的
實現實例化數據源 初始化部分連接資源
使用連接資源時從數據源中獲取
使用完畢後將連接資源歸還給數據源 環保樣的
數據源 連接池 C3P0、Durid
Spring配置數據源 連接池
數據源
開發步驟
①導入數據源的座標和數據庫驅動座標
②創建數據源對象
③設置數據源的基本連接數據
④使用數據源獲取連接資源和歸還連接資源
pom.xml導入依賴
創建數據源對象 設置數據源的基本連接數據
使用數據源獲取連接資源和歸還連接的資料
1.2 數據源的手動創建
①導入c3p0和druid的座標
<!-- C3P0連接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- Druid連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
①導入mysql數據庫驅動座標
<!-- mysql驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
②創建C3P0連接池
@Test
public void testC3P0() throws Exception {
//創建數據源
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//設置數據庫連接參數
dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("root");
//獲得連接對象
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
②創建Druid連接池
@Test
public void testDruid() throws Exception {
//創建數據源
DruidDataSource dataSource = new DruidDataSource();
//設置數據庫連接參數
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
//獲得連接對象
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
我們可以把公共的提取出來 driver、url、username、password等等
③提取jdbc.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
④讀取jdbc.properties配置文件創建連接池
@Test
public void testC3P0ByProperties() throws Exception {
//加載類路徑下的jdbc.properties
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(rb.getString("jdbc.driver"));
dataSource.setJdbcUrl(rb.getString("jdbc.url"));
dataSource.setUser(rb.getString("jdbc.username"));
dataSource.setPassword(rb.getString("jdbc.password"));
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
1.3 Spring配置數據源
Spring來搞
可以將DataSource的創建權交由Spring容器去完成
DataSource有無參構造方法,而Spring默認就是通過無參構造方法實例化對象的
DataSource要想使用需要通過set方法設置數據庫連接信息,而Spring可以通過set方法進行字符串注入
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--加載外部的properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置組件掃描-->
<context:component-scan base-package="cn.liuawen"/>
</beans>
測試從容器當中獲取數據源
@Test
//測試Spring容器產生數據源對象
public void test4() throws Exception {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = app.getBean(DataSource.class);
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
1.4 抽取jdbc配置文件
applicationContext.xml加載jdbc.properties配置文件獲得連接信息。
首先,需要引入context命名空間和約束路徑:
命名空間:xmlns:context=“http://www.springframework.org/schema/context”
約束路徑:http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
applicaitonContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--加載外部的properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置組件掃描-->
<context:component-scan base-package="cn.liuawen"/>
</beans>
1.5 知識要點
Spring容器加載properties文件
<!--加載外部的properties文件-->
<context:property-placeholder location="xx.properties"/>
<property name="" value="${key}"/>
2. Spring註解開發
Spring註解開發
2.1 Spring原始註解
Spring是輕代碼而重配置的框架,配置比較繁重,影響開發效率,所以註解開發是一種趨勢,註解代替xml配置文件可以簡化配置,提高開發效率。
配置 約定 默認
配置繁瑣 配置地獄 註解開發 註解代替xml配置文件可以簡化配置 開發效率
Spring原始註解主要是替代的配置
配置 替代
@Controller 使用在web層類上用於實例化Bean
註解 | 說明 |
---|---|
@Component | 使用在類上用於實例化Bean |
@Controller | 使用在web層類上用於實例化Bean |
@Service | 使用在service層類上用於實例化Bean |
@Repository | 使用在dao層類上用於實例化Bean |
@Autowired | 使用在字段上用於根據類型依賴注入 |
@Qualifier | 結合@Autowired一起使用用於根據名稱進行依賴注入 |
@Resource | 相當於@Autowired+@Qualifier,按照名稱進行注入 |
@Value | 注入普通屬性 |
@Scope | 標註Bean的作用範圍 |
@PostConstruct | 使用在方法上標註該方法是Bean的初始化方法 |
@PreDestroy | 使用在方法上標註該方法是Bean的銷燬方法 |
注意:
使用註解進行開發時,需要在applicationContext.xml中配置組件掃描,作用是指定哪個包及其子包下的Bean需要進行掃描以便識別使用註解配置的類、字段和方法。
使用註解進行開發 需要在applicationContext.xml中配置組件掃描
指定哪個包及其子包下的Bean需要進行掃描以便識別使用註解配置的類、字段和方法
掃描
<!--註解的組件掃描-->
<context:component-scan base-package="cn.liuawen"></context:component-scan>
使用@Component或@Repository標識UserDaoImpl需要Spring進行實例化。
使用在類上用於實例化Bean
//<bean id="userDao" class="cn.liuawen.dao.impl.UserDaoImpl"></bean>
//@Component("userDao")
@Repository("userDao")
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("save running...");
}
}
使用@Component或@Service標識UserServiceImpl需要Spring進行實例化
使用@Autowired或者@Autowired+@Qulifier或者@Resource進行userDao的注入
注入
//@Component("userService")
@Service("userService")
public class UserServiceImpl implements UserService {
/*@Autowired
@Qualifier("userDao")*/
@Resource(name="userDao")
private UserDao userDao;
@Override
public void save() {
userDao.save();
}
}
使用@Value進行字符串的注入
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Value("注入普通數據")
private String str;
@Value("${jdbc.driver}")
private String driver;
@Override
public void save() {
System.out.println(str);
System.out.println(driver);
System.out.println("save running... ...");
}
}
使用@Scope標註Bean的範圍
//@Scope("prototype")
@Scope("singleton")
public class UserDaoImpl implements UserDao {
//此處省略代碼
}
使用@PostConstruct標註初始化方法,使用@PreDestroy標註銷燬方法
@PostConstruct
public void init(){
System.out.println("初始化方法....");
}
@PreDestroy
public void destroy(){
System.out.println("銷燬方法.....");
}
//<bean id="userService" class="cn.liuawen.service.impl.UserServiceImpl">
//@Component("userService")
@Service("userService")
//@Scope("prototype")
@Scope("singleton")
public class UserServiceImpl implements UserService {
@Value("${jdbc.driver}")
private String driver;
//<property name="userDao" ref="userDao"></property>
//@Autowired //按照數據類型從Spring容器中進行匹配的
//@Qualifier("userDao") //是按照id值從容器中進行匹配的 但是主要此處@Qualifier結合@Autowired一起使用
@Resource(name="userDao") //@Resource相當於@Qualifier+@Autowired
private UserDao userDao;
public void save() {
System.out.println(driver);
userDao.save();
}
@PostConstruct
public void init(){
System.out.println("Service對象的初始化方法");
}
@PreDestroy
public void destory(){
System.out.println("Service對象的銷燬方法");
}
}
2.2 Spring新註解
使用上面的註解還不能全部替代xml配置文件,還需要使用註解替代的配置如下:
非自定義的Bean的配置:
加載properties文件的配置:context:property-placeholder
組件掃描的配置:context:component-scan
引入其他文件:
註解 | 說明 |
---|---|
@Configuration | 用於指定當前類是一個 Spring 配置類,當創建容器時會從該類上加載註解 |
@ComponentScan | 用於指定 Spring 在初始化容器時要掃描的包。 作用和在 Spring 的 xml 配置文件中的 <context:component-scan base-package=“cn.liuawen”/>一樣 |
@Bean | 使用在方法上,標註將該方法的返回值存儲到 Spring 容器中 |
@PropertySource | 用於加載.properties 文件中的配置 |
@Import | 用於導入其他配置類 |
@Configuration
@ComponentScan
@Import
@Configuration
@ComponentScan("cn.liuawen")
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {
}
//標誌該類是Spring的核心配置類
@Configuration
//<context:component-scan base-package="cn.liuawen"/>
@ComponentScan("cn.liuawen")
//<import resource=""/>
@Import({DataSourceConfiguration.class})
public class SpringCofiguration {
}
@PropertySource
@value
配置信息導入
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
//<context:property-placeholder location="classpath:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource") //Spring會將當前方法的返回值以指定名稱存儲到Spring容器中
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
@Bean
@Bean("dataSource") //Spring會將當前方法的返回值以指定名稱存儲到Spring容器中
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
測試加載核心配置類創建Spring容器
@Test
public void testAnnoConfiguration() throws Exception {
ApplicationContext applicationContext = new
AnnotationConfigApplicationContext(SpringConfiguration.class); UserService userService = (UserService)
applicationContext.getBean("userService");
userService.save();
DataSource dataSource = (DataSource)
applicationContext.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
3. Spring整合Junit
3.1 原始Junit測試Spring的問題
在測試類中,每個測試方法都有以下兩行代碼:
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
這兩行代碼的作用是獲取容器,如果不寫的話,直接會提示空指針異常。所以又不能輕易刪掉。
3.2 上述問題解決思路
讓SpringJunit負責創建Spring容器,但是需要將配置文件的名稱告訴它
將需要進行測試Bean直接在測試類中進行注入
3.3 Spring集成Junit步驟
①導入spring集成Junit的座標
②使用@Runwith註解替換原來的運行期
③使用@ContextConfiguration指定配置文件或配置類
④使用@Autowired注入需要測試的對象
⑤創建測試方法進行測試
3.4 Spring集成Junit代碼實現
①導入spring集成Junit的座標
<!--此處需要注意的是,spring5 及以上版本要求 junit 的版本必須是 4.12 及以上-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
②使用@Runwith註解替換原來的運行期
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {
}
③使用@ContextConfiguration指定配置文件或配置類
@RunWith(SpringJUnit4ClassRunner.class)
//加載spring核心配置文件
//@ContextConfiguration(value = {"classpath:applicationContext.xml"})
//加載spring核心配置類
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
}
④使用@Autowired注入需要測試的對象
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
}
⑤創建測試方法進行測試
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})public class SpringJunitTest {
@Autowired
private UserService userService;
@Test
public void testUserService(){
userService.save();
}
}
Spring集成Junit步驟
①導入spring集成Junit的座標
②使用@Runwith註解替換原來的運行期
③使用@ContextConfiguration指定配置文件或配置類
④使用@Autowired注入需要測試的對象
⑤創建測試方法進行測試
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {SpringCofiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test1() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
}
4、記錄
簡單記錄筆記 - JavaEE在線就業班2.0
的筆記