测试spring的注入
第一种
package com.shaokp.hrm.conn;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration("classpath:spring/applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class ConnTest {
@Autowired
private DataSource ds;
@Test
public void getConn() throws Exception{
Connection conn = ds.getConnection();
String sql = "select * from user_inf";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs =ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString("loginname"));
}
}
}
第二种
test:
package dao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import entity.User;
public class demo {
@Test
public void pp(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("xml/spring.xml");
System.out.println("-----容器创建-----");
User user = (User)ac.getBean("user");
System.out.println(user.getName());
System.out.println(user);
}
}
bean
package entity;
public class User {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
spring
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="user" class="entity.User">
<property name="name" value="你好!" />
<property name="age" value="世界" />
</bean>
</beans>