Spring之DI應用及JDBC模板

Spring之DI應用及JDBC模板

內容

1.DI應用之Setter方式屬性注入
2.DI應用之Contructor方式屬性注入
3.DI應用之P命名空間屬性注入
4.DI應用之屬性自動注入
5.DI應用之註解的使用
6.Spring之JDBC模板

一.使用Setter方法進行屬性注入

1.簡單類型屬性的注入(8種基本類型及String類型)

//User
public class User {

private int id;
private String username;
private String password;
private Date birthday;

//省略setter和getter
}

<beans>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">




<bean>
<property>
<property>
<property>
<property>
/<bean>
/<beans>

2.pojo類型屬性注入


//User
public class User {

private int id;
private String username;
private String password;
private Date birthday;
private Address address;

//省略setter和getter
}

//Address

public class Address {

private int id;
private String addrname;

//省略setter和getter
}

<bean>
<property>

<property>
<property>
<property>

<property>

/<property>
/<bean>

<bean>
<property>
<property>
/<bean>

3.集合屬性注入


//User
public class User {

private Map<string> map;
private Set<string> set;
private List<object> list;
//省略setter和getter
}

<bean>
<property>

<list>
<value>list1/<value>
<value>list2/<value>
<value>list3/<value>



<bean>
<property>
<property>
<property>
/<bean>
/<list>
/<property>
/<bean>

<bean>
<property>
<property>
/<bean>

<bean>
<property>


<value>set1/<value>
<value>set2/<value>
<value>set3/<value>

/<property>
/<bean>


<bean>

<property>


<entry>

<value>key1/<value>
<value>val1/<value>
/<entry>
<entry>
<value>key2/<value>
<value>val2/<value>
/<entry>
<entry>
<value>key3/<value>
<value>val3/<value>
/<entry>

/<property>
/<bean>

/<object>/<string>/<string>

4.properties對像屬性注入


//User
public class User {

private Properties props;
//省略setter和getter
}

<bean>

<property>
<props>
<prop>prop1/<prop>
<prop>prop2/<prop>
<prop>prop3/<prop>
/<props>
/<property>
/<bean>

二.Contructor方式屬性注入

1.步驟


1.定義有參構造方法(一般還需要提供無參構造)
2.在applicationContext.xml文件使用<constructor-arg>標籤設置即可
/<constructor-arg>

2.代碼



<beans>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">


<bean>
<constructor-arg>
<constructor-arg>
<constructor-arg>
<constructor-arg>
<constructor-arg>
/<bean>

<bean>

<property>
<property>
/<bean>
/<beans>

3.測試


@Test
public void testDI1(){
//使用構造器來實例化對像

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

User user = ac.getBean("user", User.class);
System.out.println(user.getId()+","+user.getUsername()+","+user.getPassword()+","+user.getAddr().getAddrname());

}

4.優缺點


優點:
1.比setter效率高。
缺點:
1.業務邏輯比較複雜,需要重載很多的構造方法,導致代碼的書寫及維護工作變的很難。

注意:一般不推薦使用構造方式注入。

三.P命名空間屬性注入

1.步驟


1.在applicationContext.xml文件頭部加上P命名空間
"xmlns:p="http://www.springframework.org/schema/p"
2.在bean標籤中使用p:屬性的方式來進行屬性注入。

2.代碼



<beans>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">


<bean>

/<beans>

四.屬性自動注入

1.步驟


注意:只適用於pojo類型的自動注入
1.指定屬性自動注入的方式(default|no|byName|byType|constructor)
其中no|byName|byType會經常使用

2.代碼



<beans>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" >




<bean>

<bean>

<bean>
<property>
<property>
/<bean>
/<beans>

3.測試


@Test
public void testDI3(){
//自動屬性注入(byName)
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

User user = ac.getBean("user3", User.class);

System.out.println(user.getUsername()+","+user.getAddr().getAddrname());

}

@Test
public void testDI4(){
//自動屬性注入(byType)
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

User user = ac.getBean("user4", User.class);

System.out.println(user.getUsername()+","+user.getAddr().getAddrname());

}

五.註解的使用

1.常用IOC註解


1.@Component:
一般使用在類上,spring會掃描該註解對應類,併為該類創建對像。
MVC分層時,一般該註解應用於Controller層,Service層,Dao層
2.@Controller:
和@Component用法一樣

MVC分層時,一般該註解應用於Controller層
3.@Service
和@Component用法一樣
MVC分層時,一般該註解應用於Service層
4.@Respository:
和@Component用法一樣
MVC分層時,一般該註解應用於Dao層
5.@Autowire:
一般用於pojo類型屬性上,會從spring容器中織入對像到相應的屬性上去(按byType來織入)。
6.@Qulifier:
一般用於pojo類型屬性上,和@Autowired配合使用,轉化為按bean的名稱指定(按byName來織入)
7.@Resource:
一般用於pojo類型屬性上,指定bean的名稱去織入(按byName來織入),替代 5和 6註解。
8.@PostConstruct
一般用於方法上,表示調用構造器之後要執行的方法,等同於init-method
9.@PreDestroy
一般用於方法上,表示對像銷燬前要執行的方法,等同於destory-method
10.@Scope
一般用於類上,表示對像生命週期(作用域 singleton|prototype|request|session|global session)

2.使用步驟


1.在applicationContext.xml文件頭部引入命名空間

xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
2.在applicationContext.xml中使用<component-scan>
掃描指定包下的類,如果該類有上述IOC註解,就會為該類創建對像。
3.在類上和屬性上使用合適的註解即可。
/<component-scan>

3.代碼



<beans>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"

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" >


<component-scan>

/<beans>

Dao層


//spring容器會創建UserDao類的對像
//其中value屬性作用是:為該對像指定name值,即相當於UserDao dao = new UserDao()

//如果沒指定value值,則默認會使用類名第一個字母小寫的方式作為該bean的name,即userDao為name值。
@Repository(value="dao")
public class UserDao {

public User selectById(int id){

User user = new User();
user.setId(1);

return user;
}
}

Service層


//spring容器會創建UserService類的對像
//其中value屬性作用:為該容器中該對像指定name值,相當於UserService ser = new UserService()
@Service(value="ser")
public class UserService {

//該註解表示按名稱自動織入UserDao對像。name表示容器中UserDao對像的name值。
//可以替代 @Autowired和@Qualifier註解
@Resource(name="dao")
//也可以使用該註解進行屬性自動織入(按類型織入)
//也可和@Resource()註解一起使用 (按名稱織入),其中value屬性表示bean的name值
@Autowired
@Qualifier(value="dao")
private UserDao dao;


public User findById(int id){


return dao.selectById(id);
}

}

4.測試


@Test
public void testAnno(){

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-anno.xml");

UserService ser = ac.getBean("ser", UserService.class);

User user = ser.findById(1);

System.out.println(user);

}

六.Spring集成單元測試

1.原因


一般會把spring容器中的對像,織入到單元測試類中,不需要手動創建對像,使用管理。

2.步驟


1.引入spring-test.jar

2.在單元測試類上使用註解@ContextConfiguration和@RunWith
@ContextConfiguration用來加載applicationContext.xml文件
相當於ApplicationContext ac = new ClasspathXmlApplicationContext(String location);
@RunWith用來實例化SpringJUnit4ClassRunner類對像的
3.在單元測試的屬性上使用@Autowired織入對像

3.代碼


@RunWith(value=SpringJUnit4ClassRunner.class)
//classpath:該前綴的作用是直接定位到工程中classess文件夾下
@ContextConfiguration(value={"classpath:applicationContext-anno.xml"})
public class SpringTest {

@Autowired
UserService ser;

@Test
public void testDI(){

User user = ser.findById(1);

System.out.println(user);
}
}

七.Spring之JDBC模板

1.為什麼使用JDBCTemplate


Spring JDBC是Spring所提供的持久層技術,它的主要目標是降低使用JDBC API的門檻,以一種更直接,更簡潔,更

簡單的方式使用JDBC API, 在Spring JDBC裡,僅需做那些與業務相關的DML操作,而將資源獲取,Statment創建,
資源釋放以及異常處理等繁雜而乏味的工作交給Spring JDBC.
雖然ORM的框架已經成熟豐富,但是JDBC的靈活,直接的特性,依然讓他擁有自己的用武之地,如在完全依賴查詢
模型動態產生查詢語句的綜合查詢系統中,Hibernaye,MyBatis,JPA等框架都無法使用,這裡JDBC是唯一的選擇.

2.使用步驟

2.1 引入jar包依賴



<dependency>
<groupid>org.springframework/<groupid>
<artifactid>spring-jdbc/<artifactid>
<version>4.2.8.RELEASE/<version>
/<dependency>


<dependency>
<groupid>com.mchange/<groupid>
<artifactid>c3p0/<artifactid>
<version>0.9.5.2/<version>
/<dependency>


<dependency>
<groupid>mysql/<groupid>
<artifactid>mysql-connector-java/<artifactid>

<version>5.1.40/<version>
/<dependency>

2.2 使用JdbcTemplate模板Api


//Spring操作數據模板類(工具類)
JdbcTemplate
//DML操作(增刪改)
JdbcTemplate.update(sql,ArgsObj....);
//DDL|DCL操作
JdbcTemplate.execute(sql)
//DQL查詢單個數據
jdbcTemplate.queryForObject(String sql, RowMapper var2, Object... var3);
//查詢所有數據List
jdbcTemplate.query(String sql, RowMapper var2, Object... var3);
//返回List>
jdbcTemplate。queryForList(String sql,Object... var3)

//注意:
其中RowWapper 將結果封裝的處理器; 得到Result解析成實體類對象即可!

2.3 引入資源文件


driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/javaee

user=root
password=tiger

2.5 Spring上下文配置



<beans> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">


<component-scan>


<property-placeholder>


<bean>
<property>
<property>
<property>
<property>
/<bean>


<bean>
<property>
/<bean>
/<beans>

2.6 把模板對像織入Dao層


@Repository
public class StudentDao {
//注意:JdbcTemplate是線程安全的,可以直接作為全局變量使用
@Autowired
private JdbcTemplate temp;

//增
public void insert(Student stu){
temp.update("insert into student(sname) values(?)", new Object[]{stu.getSname()});
}
//刪
public void delete(int id){
temp.update("delete from student where id = ?", id);
}
//改
public void update(Student stu){
temp.update("update student set sname=? where id=?", stu.getSname(),stu.getId());
}
//查單個對像
public Student selectById(Integer id){

Student stu = temp.queryForObject("select * from student where id = ?",new RowMapper<student>(){
@Override
public Student mapRow(ResultSet resultset, int i) throws SQLException {

Student stu = beanHandler(resultset);

return stu;
}},id);

return stu;
}
//查總記錄數
public int selectCount(){
int count = temp.queryForObject("select count(*) from Student",Integer.class);
return count;
}
//查所有
public List<student> selectAll(){
List<student> stu = temp.query("select * from student", new RowMapper<student>(){
@Override
public Student mapRow(ResultSet resultset, int i) throws SQLException {


Student stu = beanHandler(resultset);

return stu;
}
});
return stu;
}

/**
* Bean封裝處理器
* @param resultset
* @return
*/
public Student beanHandler(ResultSet rs){

Student stu = new Student();
try {
int id = rs.getInt("id");
String sname = rs.getString("sname");
stu.setId(id);
stu.setSname(sname);
} catch (SQLException e) {
e.printStackTrace();
}

return stu;
}
}

/<student>/<student>/<student>/<student>

2.7 測試


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value="classpath:applicationContext-jdbc.xml")
public class TestJDBC2 {

@Autowired
StudentDao dao;

@Test
public void testSave(){

Student stu = new Student();
stu.setSname("張三");
dao.insert(stu);

}

@Test
public void testRemove(){

dao.delete(3);

}

@Test
public void testModify(){

Student stu = new Student();
stu.setId(1);
stu.setSname("張三");
dao.update(stu);
}

@Test
public void testFindById(){

Student stu = dao.selectById(1);
System.out.println(stu.getSname());
}

@Test
public void testFindAll(){

List<student> list =dao.selectAll();

System.out.println(list);

}

@Test
public void testFindCount(){

int i = dao.selectCount();
System.out.println(i);
}
}
/<student>


分享到:


相關文章: