1. 程式人生 > >Spring核心之4 SpringIOC容器的例項化

Spring核心之4 SpringIOC容器的例項化

1.SpringIOC容器-bean屬性setter方法注入

1.1 概述

利用Spring的配置檔案Beans002.xml 配置bean並且setter方法引數注入JDBCDataSource的連結引數, 這樣Spring在建立JDBCDataSource物件以後會自動化的呼叫setter方法注入資料庫連線引數

1.2 beans002.xml配置檔案

<bean id="dataSource" class="com.gaoxinfu.demo.spring.example.dao.JDBCDataSource">
    <property name="driver" value=
"oracle.jdbc.OracleDriver"></property> <property name="url" value="dbc:oracle:thin:@localhost:1521:xe"></property> <property name="user" value="test001"></property> <property name="password" value="test001"></property> </bean>

1.3 程式碼

import java.
io.Serializable; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * * @Description:JDBCDataSource * @Author:gaoxinfu * @Time:2018年2月12日 下午4:36:03 */ @SuppressWarnings("serial") public class JDBCDataSource implements Serializable{ private String driver;
private String url; private String user; private String password; public String getDriver() { return driver; } public void setDriver(String driver) { try { //註冊資料庫驅動 Class.forName(driver); this.driver = driver; } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Connection getConnection() throws SQLException { Connection connection=DriverManager.getConnection(url, user, password); return connection; } public void close(Connection connection) { if (connection!=null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }

1.4 測試


import java.sql.Connection;
import java.sql.SQLException;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gaoxinfu.demo.base.Base;

public class JDBCDataSourceTest extends Base{

	@Test
	public void testJDBCDataSourceBean() throws SQLException {
		String beanConfig="Beans002.xml";
		ApplicationContext context =new ClassPathXmlApplicationContext(beanConfig);
		JDBCDataSource jDBCDataSource= context.getBean("dataSource",JDBCDataSource.class);
		Connection connection=jDBCDataSource.getConnection();
		logger.info("JDBCDataSourceTest-testJDBCDataSourceBean:connection="+connection);
	}
}

2.SpringIOC容器-利用構造器引數實現依賴注入

2.1 概述

通過構造方法去注入

2.2 bean002.xml配置

<!-- 呼叫OracleUserDAO的構造方法 public OracleUserDAO(JDBCDataSource dataSource)  -->
<bean id="userDAO" class="com.gaoxinfu.demo.spring.example.dao.OracleUserDAO">
	<!-- 利用構造器引數注入bean屬性 -->
	<constructor-arg index="0" ref="dataSource"></constructor-arg>
</bean>

2.3 程式碼

2.3.1 UserDAO

package com.gaoxinfu.demo.spring.example.dao;

import com.gaoxinfu.demo.spring.example.bean.User;

public interface UserDAO {

	public User findByName(String name);
}

2.3.2 OracleUserDAO

package com.gaoxinfu.demo.spring.example.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.gaoxinfu.demo.base.Base;
import com.gaoxinfu.demo.spring.example.bean.User;

public class OracleUserDAO extends Base implements UserDAO {

	private JDBCDataSource dataSource;
	
	/**
	 *  構造方法
	 * @param dataSource
	 */
	public OracleUserDAO(JDBCDataSource dataSource) {
		super();
		this.dataSource = dataSource;
	}

	@Override
	public User findByName(String name) {
		logger.info("利用JDBC技術查詢User資訊");
//		String sql="Select * From Users Where Name=?";
		String sql="Select id,name,pwd,phone From Users Where Name=?";
		Connection connection=null;
		try {
			connection=dataSource.getConnection();
			PreparedStatement preparedStatement=connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			ResultSet resultSet=preparedStatement.executeQuery();
			User user=null;
			while (resultSet.next()) {
				user=new User();
				user.setId(resultSet.getInt("id"));
				user.setName(resultSet.getString("name"));
				user.setPhone(resultSet.getString("phone"));
				user.setPwd(resultSet.getString("pwd"));
			}
			resultSet.close();
			connection.close();
			return user;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			logger.info("OracleUserDAO-findByName出現異常:"+e);
			throw new RuntimeException(e);
		}finally {
			dataSource.close(connection);
		}
	}
}

2.4 測試

package com.gaoxinfu.demo.spring.example.dao;

import java.sql.SQLException;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gaoxinfu.demo.base.Base;

public class OracleUserDAOTest extends Base{

	@SuppressWarnings("resource")
	@Test
	public void testFindByName() throws SQLException {
		String beanConfig="Beans002.xml";
		ApplicationContext context =new ClassPathXmlApplicationContext(beanConfig);
		UserDAO userDAO=context.getBean("userDAO",UserDAO.class);
		logger.info(userDAO.findByName("Tom"));
	}
}

3.SpringIOC容器-利用Spring的自動裝配功能實現自動屬性注入

3.1概述

3.1.1 當前自動注入型別有一下幾種

1.no 禁用自動裝配,預設值 2.byName 根據屬性名自動裝配,此選項將檢查容器並根據名字查詢與屬性完全一致的bean,並將其與屬性自動裝配; 3.byType 如果容器中存在一個與指定屬性型別相同的bean,那麼將與該屬性自動裝配 4.constructor 與byType的方式類似,不同之處在於它應用於構造引數 5.autodetect 通過bean類來決定使用constructor還是byType方法自動裝配,如果發現預設的構造器,那麼將使用byType方式

下面的是byType的一個案例

3.2 bean002.xml配置

 <!-- 自動裝配功能 -->
    <bean id="userService" class="com.gaoxinfu.demo.spring.example.service.UserService" autowire="byType"></bean>

3.3 程式碼

package com.gaoxinfu.demo.spring.example.service;

import com.gaoxinfu.demo.spring.example.bean.User;
import com.gaoxinfu.demo.spring.example.dao.UserDAO;

public class UserService {

	private UserDAO userDAO;
	
	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	/**
	 * 
	 * @Title: login   
	 * @Description: 使用者登入功能
	 * @param name
	 * @param pwd
	 * @return      
	 * @return: User      
	 * @throws   
	 * @Exception:
	 * @Author: gaoxinfu
	 * @Time:2018年2月12日 下午4:50:22
	 */
	public User login(String name,String pwd) {
		User user=userDAO.findByName(name);
		if (user!=null&&pwd.equals(user.getPwd())) {
			return user;
		}
		return null;
	}
}


3.4 測試

package com.gaoxinfu.demo.spring.example.service;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gaoxinfu.demo.base.Base;

public class UserServiceTest extends Base{

	@SuppressWarnings("resource")
	@Test
	public void testLogin() {
		String beanConfig="Beans002.xml";
		ApplicationContext context =new ClassPathXmlApplicationContext(beanConfig);
		UserService UserService=context.getBean("userService",UserService.class);
		logger.info(UserService.login("Tom", "123"));
	}

}