原文链接:http://blog.csdn.net/qq_22329521/article/details/75000091
第一步导包
配置约束
在src下创建applicationContext.xml文件
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
</beans>
创建对象
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<!--将User交给spring管理-->
<!--Bean元素:使用该元素描述需要spring容器管理的对象
name属性:给被管理的对象七个名字,获得对象时根据该名称获取对象,名称可以使用,可以重复
class属性:被管理对象的完整类名
id属性:与name属性一模一样,名称不可重复,不能使用特殊字符
尽量使用name-->
<!--空参创建-->
<!--scope:
singleton(默认值):只会存在一个实例
prototype:每次都会创建
-->
<!--
init-method 创建好对象执行某个方法,
destroy-mothod:销毁对象会执行方法-->
<bean name="user" class="com.fmt.spring.bean.User"
init-method="init" destroy-method="destory"></bean>
<!--静态方法创建-->
<bean name="user1" class="com.fmt.spring.bean.UserFactory" factory-method="createUser"></bean>
<!--实例工程创建-->
<bean name="userfactory" class="com.fmt.spring.bean.UserFactory" ></bean>
<bean name="user2" factory-bean="userfactory" factory-method="createUser2"></bean>
<!--导入其他spring的配置文件-->
<import resource="com/fmt/spring/test/applicationContext.xml"></import>
</beans>
public class User {
private String name;
private Integer age;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void init(){
System.out.println("init");
}
public void destory(){
System.out.println("destory");
}
}
public class UserFactory {
public static User createUser(){
return new User();
}
public User createUser2(){
return new User();
}
}
@Test
public void fun1(){
//1.创建容器
ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//2.向容器要user对象(第一种)
User user = (User) ac.getBean("user");
//2.向容器要user对象(第二种)
User user = (User) ac.getBean("user1");
//2.向容器要user对象(第三种)
User user = (User) ac.getBean("user2");
//打印user
System.out.println(user);
//容器关闭
ac.close();
}
属性注入
(set方法注入)
<bean name="user" class="com.fmt.spring.bean.User">
<property name="name" value="tom"></property>
<property name="age" value="19"></property>
<property name="car" ref="car"></property>
</bean>
<bean name="car" class="com.fmt.spring.bean.Car">
<property name="name" value="bwm"></property>
<property name="color" value="red"></property>
</bean>
构造函数注入
<bean name="user1" class="com.fmt.spring.bean.User">
<constructor-arg name="name" value="tom"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="car" ref="car1"></constructor-arg>
</bean>
<bean name="car1" class="com.fmt.spring.bean.Car">
<constructor-arg name="name" value="bwm" index="0"></constructor-arg>
<constructor-arg name="color" value="red" index="1"></constructor-arg>
</bean>
//为了避免有多个构造函数指定不了映入index和type
<bean name="user2" class="com.fmt.spring.bean.User">
<!--name属性:构造函数的参数名
index属性:构造函数的参数索引
type属性:构造函数的的参数类型-->
<constructor-arg name="name" value="999" index="0" type="java.lang.Integer"></constructor-arg>
<constructor-arg name="car" ref="car1" index="1"></constructor-arg>
</bean>
<!--p 命名空间注入
1.导入p名称空间 xmlns:p="http://www.springframework.org/schema/p"
2.使用p:属性完成注入
-值类型:p:属性名="值"
-对象类型:p:属性名-ref="bean名称"
-->
<bean name="user3" class="com.fmt.spring.bean.User" p:age="10" p:name="jack" p:car-ref="car">
</bean>
<!--
spel注入:sprig Expression Language spring表达式语言
-->
<bean name="user4" class="com.fmt.spring.bean.User">
<property name="name" value="#{user3.name}"></property>
<property name="age" value="#{user3.age}"></property>
<property name="car" ref="car"></property>
</bean>
<!--复杂类型注入-->
<!--array注入-->
<bean name="cb" class="com.fmt.spring.bean.CollectionBean">
<!--如果数组中只准备注入一个值直接使用value或ref-->
<!--<property name="arr" value="tom"></property>-->
<!--多个元素注入-->
<property name="arr">
<array>
<value>tom</value>
<value>jack</value>
<ref bean="user4"></ref>
</array>
</property>
<property name="list">
<array>
<value>1</value>
<value>2</value>
<ref bean="user4"></ref>
</array>
</property>
<property name="map">
<map>
<entry key="url" value="www.baidu.com"></entry>
<entry key="xka" value="显卡"></entry>
<entry key-ref="user3" value-ref="user2"></entry>
</map>
</property>
<property name="properties">
<props>
<prop key="bianma">utf-8</prop>
<prop key="max">8m</prop>
</props>
</property>
</bean>
public class User {
private String name;
private Integer age;
private Car car;
public User() {
System.out.println("无参构造函数");
}
public User(String name, Integer age, Car car) {
this.name = name;
this.age = age;
this.car = car;
}
public User(String name, Car car) {
System.out.println("User(String name, Car car)!!");
this.name = name;
this.car = car;
}
public User(Car car,String name) {
System.out.println("User(Car car,String name)!!");
this.name = name;
this.car = car;
}
public User(Integer name, Car car) {
System.out.println("User(Integer name, Car car)!!");
this.name = name+"";
this.car = car;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void setName(String name) {
this.name = name;
}
public void setCar(Car car) {
this.car = car;
}
public void setAge(Integer age) {
this.age = age;
}
}
public class Car {
public String name;
public String color;
public Car() {
}
public Car(String name, String color) {
this.name = name;
this.color = color;
System.out.println("car ");
}
public void setName(String name) {
this.name = name;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
", color='" + color + '\'' +
'}';
}
}
public class CollectionBean {
private Object[] arr;
private List list;
private Map map;
private Properties properties;
public Object[] getArr() {
return arr;
}
public void setArr(Object[] arr) {
this.arr = arr;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public String toString() {
return "CollectionBean{" +
"arr=" + Arrays.toString(arr) +
", list=" + list +
", map=" + map +
", properties=" + properties +
'}';
}
}
@Test
public void fun4(){
//1.创建容器
ApplicationContext ac=new ClassPathXmlApplicationContext("com/fmt/spring/test/applicationContext.xml");
//2.向容器要user对象
User user = (User) ac.getBean("user");
//打印user
System.out.println(user);
}
注解
注解是为了代替配置
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd ">
<!--
指定扫描这个包下的所有类的注解
扫描包下,会扫描指定包下的所有包
-->
<context:component-scan base-package="com.fmt.spring.aop">
</context:component-scan>
<bean name="car2" class="com.fmt.spring.aop.Car">
<property name="name" value="兰博基尼"></property>
<property name="color" value="白色"></property>
</bean>
</beans>
//<bean name="user" class="com.fmt.spring.bean.User/>
Component("user")
@Service("user")//service层
@Controller("user")//web层
@Repository("user")//dao层
//指定对象的作用范围
Scope(scopeName = "prototype")
public class User {
@Value("tom")
public String name;
@Value("18")
public Integer age;
//自动装配,如果碰到多个类型一直的对象,将无法选择具体注入那个对象
@Autowired
public Car car;
// @Qualifier("car2")//使用注解告诉spring容器,去取那个Car对象
// public Car car2;
@PostConstruct//对象被创建后,调用init-method
public void init(){
}
@PreDestroy//对象即将被销毁钱调用,destory-method
public void destory(){
}
@Resource(name="car2")//手动注入,指定注入那个名称的bean对象
public Car car3;
@Value("jack")
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", car=" + car +
", car3=" + car3 +
'}';
}
}
使用spring与juit结合不用每次都创建容器直接使用
RunWith(SpringJUnit4ClassRunner.class)//帮我们创建容器
//指定创建容器时使用那个配置文件
ContextConfiguration("classpath:com/fmt/spring/aop/applicationContext.xml")
public class Demo {
@Resource(name="car2")
private Car car;
@Test
public void fun1(){
System.out.println(car);
}
}
aop
public interface UserInterface {
void save();
void delete();
void update();
void find();
}
public class UserInterfaceImpl implements UserInterface {
@Override
public void save() {
System.out.println("save");
}
@Override
public void delete() {
System.out.println("delete");
}
@Override
public void update() {
System.out.println("update");
}
@Override
public void find() {
System.out.println("find");
}
}
public class MyAdvice {
//前置通知:目标方法运行之前调用
public void before(){
System.out.println("前置通知");
}
//后置通知,如果方法出现异常不会调用
public void afterReturn(){
System.out.println("后置通知");
}
//环绕通知,方法之前之后都会调用
public void around(ProceedingJoinPoint pjp){
System.out.println("环绕通知之前的部分");
try {
pjp.proceed();//调用目标方法
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("这是后置通知(如果出现异常不会调用)!!");
}
//异常通知
public void afterException(){
System.out.println("异常时调用");
}
//后置通知出现异常也会调用
public void after(){
System.out.println("这是后置通知(出现异常也会调用)");
}
}
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
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-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置目标对象-->
<bean name="userServiceTarget" class="com.fmt.spring.service.UserInterfaceImpl">
</bean>
<!--配置通知对象-->
<bean name="myAdvice" class="com.fmt.spring.service.MyAdvice">
</bean>
<!--配置将通知织入对象-->
<aop:config>
<!--配置切入点
public void com.fmt.spring.service.UserInterfaceImpl.save()
void com.fmt.spring.service.UserInterfaceImpl.save()
* com.fmt.spring.service.UserInterfaceImpl.*()
* com.fmt.spring.service.UserInterfaceImpl.*(..)
* com.fmt.spring.service.*InterfaceImpl.*(..)
* com.fmt.spring.service..*InterfaceImpl.*(..)
-->
<aop:pointcut id="pc" expression="execution(public void com.fmt.spring.service.UserInterfaceImpl.save())"></aop:pointcut>
<!--指定敏给before作为前置通知,切入到pc这个方法中-->
<aop:aspect ref="myAdvice">
<aop:before method="before" pointcut-ref="pc"></aop:before>
<!--后置-->
<aop:after-returning method="afterReturn" pointcut-ref="pc"></aop:after-returning>
<!--环绕-->
<aop:around method="around" pointcut-ref="pc"></aop:around>
<!--异常拦截通知-->
<aop:after-throwing method="afterException" pointcut-ref="pc"></aop:after-throwing>
<!--后置-->
<aop:after method="after" pointcut-ref="pc"></aop:after>
</aop:aspect
>
</aop:config>
</beans>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:com/fmt/spring/springaop/applicationContext.xml")
public class DemoTest {
@Resource(name= "userServiceTarget")
private UserInterface us;
@Test
public void fun1(){
us.save();
}
}
注解配置
//通知类
@Aspect
//表示该类是通知类
public class MyAdvice {
//前置通知:目标方法运行之前调用
@Before("execution(* com.fmt.spring.service..*InterfaceImpl.*(..))")
public void before(){
System.out.println("前置通知");
}
//后置通知,如果方法出现异常不会调用
@AfterReturning("execution(* com.fmt.spring.service..*InterfaceImpl.*(..))")
public void afterReturn(){
System.out.println("后置通知");
}
//环绕通知,方法之前之后都会调用
@Around("execution(* com.fmt.spring.service..*InterfaceImpl.*(..))")
public void around(ProceedingJoinPoint pjp){
System.out.println("环绕通知之前的部分");
try {
pjp.proceed();//调用目标方法
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("这是后置通知(如果出现异常不会调用)!!");
}
//异常通知
@AfterThrowing("execution(* com.fmt.spring.service..*InterfaceImpl.*(..))")
public void afterException(){
System.out.println("异常时调用");
}
//后置通知出现异常也会调用
@After("execution(* com.fmt.spring.service..*InterfaceImpl.*(..))")
public void after(){
System.out.println("这是后置通知(出现异常也会调用)");
}
}
在xml中只需要配置
<!--配置目标对象-->
<bean name="userServiceTarget" class="com.fmt.spring.service.UserInterfaceImpl">
</bean>
<!--配置通知对象-->
<bean name="myAdvice" class="com.fmt.spring.service.MyAdvice">
</bean>
<!-- 开启使用注解完成织入-->
<aop:aspectj-autoproxy>
</aop:aspectj-autoproxy>
JDBC
@Test
public void fun1(){
//准备连接池
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
try {
comboPooledDataSource.setDriverClass("com.jdbc.mysql.jdbc.Driver");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
comboPooledDataSource.setJdbcUrl("jdbc:mysql:///jdbctest");
comboPooledDataSource.setUser("root");
comboPooledDataSource.setPassword("123456");
//创建JDBC末班对象
JdbcTemplate jt=new JdbcTemplate();
jt.setDataSource(comboPooledDataSource);
//书写sql语句
String sql="insert into t_user values(null,'rose')";
jt.update(sql);
}
xml配置
<!--将连接池放到spring容器里-->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="jdbc:mysql:///jdbctest"></property>
<property name="driverClass" value="com.jdbc.mysql.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--将JDBCTemple放到spring容器里-->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--将UserDao放到spring容器了-->
<bean name="userDao" class="com.fmt.spring.jdbc.UserDaoImp">
<property name="jt" ref="jdbcTemplate"></property>
</bean>
public class UserDaoImp implements UserDao {
private JdbcTemplate jt;
@Override
public void save(User user) {
String sql="insert into t_user values(null,?)";
jt.update(sql,user.name);
}
@Override
public void find(Integer id) {
String sql="select * from t_user where id=?";
jt.queryForObject(sql, (resultSet, i) -> {
User user = new User();
user.id=resultSet.getInt("id");
user.name=resultSet.getString("name");
return user;
}, id);
}
@Override
public void delete(Integer id) {
String sql="delete from t_user where id=?";
jt.update(sql,1);
}
@Override
public void update(User user) {
String sql="update t_user set name=? where id=? ";
jt.update(sql,user.name,user.id);
}
@Override
public int getTotalCount() {
String sql="select count(*) from t_user";
Integer integer = jt.queryForObject(sql, Integer.class);
return integer;
}
@Override
public List<User> getUserAll() {
String sql="select * from t_user";
List<User> list = jt.query(sql, new RowMapper<User>() {
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user = new User();
user.id = resultSet.getInt("id");
user.name = resultSet.getString("name");
return user;
}
});
return list;
}
public void setJt(JdbcTemplate jt) {
this.jt = jt;
}
public JdbcTemplate getJt() {
return jt;
}
}
@Test
public void fun2(){
//准备连接池
User user = new User();
user.name="xxx";
userDao.delete(1);
}
JdbcDaoSupport
public class UserDaoImp extends JdbcDaoSupport implements UserDao {
@Override
public void save(User user) {
String sql="insert into t_user values(null,?)";
super.getJdbcTemplate().update(sql,user.name);
}
}
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="jdbc:mysql:///jdbctest"></property>
<property name="driverClass" value="com.jdbc.mysql.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--将UserDao放到spring容器了-->
<bean name="userDao" class="com.fmt.spring.jdbc.UserDaoImp">
<property name="dataSource" ref="dataSource"></property>
</bean>
读取配置文件
db.properties
jdbc.jdbcUrl=jdbc:mysql:///jdbctest
jdbc.driverClass=com.jdbc.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
<!--指定property 读取配置文件-->
<context:property-placeholder location="classpath:com/fmt/spring/jdbc/db.properties"> </context:property-placeholder>
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
事务
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 事务核心管理器,封装了事务所有操作,依赖于连接池-->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--事务模板对象-->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property>
</bean>
<!--dao-->
<bean name="accountDao" class="com.fmt.spring.dao.AccountDaoImp">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--service-->
<bean name="accountService" class="com.fmt.spring.dao.AcountServiceImp">
<property name="ad" ref="accountDao"></property>
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean>
private TransactionTemplate transactionTemplate;
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
private AccountDao ad;
@Override
public void transfer(Integer from, Integer to, Double money) {
//事务操作
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
ad.decreaseMoeny(from,money);
ad.addMoney(to,money);
}
});
}
xml配置事务
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="transfer*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
</tx:attributes>
</tx:advice>
<!--配置织入-->
<aop:config >
<!--配置切点表达式-->
<aop:pointcut id="txtPc" expression="execution(* com.fmt.spring.dao.*ServiceImp.*(..))"></aop:pointcut>
<!--配置切面
advice-ref :通知名称
pointcut-ref:切点的名称
-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txtPc"></aop:advisor>
</aop:config>
注解配置
非常非常容易
xml中加入
<!--开启注解管理aop事务-->
<tx:annotation-driven/>
@Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED)
public class AcountServiceImp implements AcountService{
public void setAd(AccountDao ad) {
this.ad = ad;
}
private AccountDao ad;
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ)
public void transfer(Integer from, Integer to, Double money) {
ad.decreaseMoeny(from,money);
int i=20/0;
ad.addMoney(to,money);
}
}
SSH整合
- spring与struct2整合,是将action对象 交给spring容器负责创建
- spring与hibernate整合,是将sessionFactory交给spring来负责维护spring,来维护以及aop事务
基本目录结构
Spring整合struts2
配置 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--让spring随web启动而启动-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置文件位置参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--struct2-->
<filter >
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!--struts2 与spring 整合
struts.objectFactory=spring 将action 交给spring容器
struts.objectFactory.spring.autoWire=name spring负责装配action 的属性
-->
<constant name="struts.objectFactory" value="spring"></constant>
<package name="" namespace="/" extends="struts-default">
<!--整合方案一 class属性上任然配置action的完整类名
struts2仍然创建action,由spring负责组装Action的依赖属性-->
<!--<action name="UserAction_*" class="com.fmt.ssh.action.UserAction" method="{1}">-->
<!--<result name="success">/hehe.jsp</result>-->
<!--</action>-->
<!--方案2 class属性填写spring中action对象的BeanName
完全由spring来管理生命周期,包括action的创建-->
<action name="UserAction_*" class="userAction" method="{1}">
<result name="success">/hehe.jsp</result>
</action>
</package>
</struts>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<bean name="userAction" class="com.fmt.ssh.action.UserAction" scope="prototype">
<property name="us" ref="userServiceImp"></property>
</bean>
<!--service配置 -->
<bean name="userServiceImp" class="com.fmt.ssh.service.UserServiceImp">
</bean>
<bean name="userAction" class="com.fmt.ssh.action.UserAction" scope="prototype">
//此处是spring手动配置,需要在上方struts.xml中配置class="userAction" ,如果class设置为包名+类名,此处可以不配置,但是如果要把UserServiceImp加载进来,bean中的name需要和userAction中的 UserService 名字相同
<property name="us" ref="userServiceImp"></property>
</bean>
<!--service配置 -->
<bean name="userServiceImp" class="com.fmt.ssh.service.UserServiceImp">
</bean>
</beans>
public class UserAction extends ActionSupport{
private UserService us;
public void setUs(UserService us) {
this.us = us;
}
@Override
public String execute() throws Exception {
System.out.println(us);
return super.execute();
}
}
配置到这访问http://localhost:8080/UserAction_execute 看是否成功
spring 整合hibernate
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库url -->
<property name="hibernate.connection.url">jdbc:mysql:///jdbctest</property>
<!-- 数据库连接用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 数据库连接密码 -->
<property name="hibernate.connection.password">123456</property>
<!-- 数据库方言
注意: MYSQL在选择方言时,请选择最短的方言.
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 将hibernate生成的sql语句打印到控制台 -->
<property name="hibernate.show_sql">true</property>
<!-- 将hibernate生成的sql语句格式化(语法缩进) -->
<property name="hibernate.format_sql">true</property>
<!--
自动导出表结构. 自动建表
-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 引入实体配置文件 -->
<mapping resource="com/fmt/ssh/domain/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<!--将SessionFactory配置到spring容器中-->
<!--加载配置方案1:任然使用外部的配置信息-->
<!--<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">-->
<!--<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>-->
<!--</bean>-->
<!--加载配置方案2:在spring中配置hibernate的配置信息-->
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="hibernateProperties">
<!--配置hibernate基本信息-->
<props>
<!--必选配置-->
<prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
<prop key="hibernate.connection.url">jdbc:mysql:///jdbctest</prop>
<prop key="hibernate.connection.username">root</prop>
<prop key="hibernate.connection.password">123456</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!--可选配置-->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!--引入orm映射,指定orm元数据所在的包路径,-->
<property name="mappingDirectoryLocations" value="classpath:com/fmt/ssh/domain"></property>
</bean>
</beans>
public class User {
/*
* CREATE TABLE `sys_user` (
`user_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`user_code` varchar(32) NOT NULL COMMENT '用户账号',
`user_name` varchar(64) NOT NULL COMMENT '用户名称',
`user_password` varchar(32) NOT NULL COMMENT '用户密码',
`user_state` char(1) NOT NULL COMMENT '1:正常,0:暂停',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
*/
private Long user_id;
private String user_code;
private String user_name;
private String user_password;
private Character user_state;
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
public String getUser_code() {
return user_code;
}
public void setUser_code(String user_code) {
this.user_code = user_code;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
public Character getUser_state() {
return user_state;
}
public void setUser_state(Character user_state) {
this.user_state = user_state;
}
@Override
public String toString() {
return "User [user_id=" + user_id + ", user_code=" + user_code + ", user_name=" + user_name + ", user_password="
+ user_password + "]";
}
}
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.fmt.ssh.domain" >
<class name="User" table="sys_user" >
<id name="user_id" >
<generator class="native"></generator>
</id>
<property name="user_code" ></property>
<property name="user_name" ></property>
<property name="user_password" ></property>
<property name="user_state" ></property>
</class>
</hibernate-mapping>
测试Hibernate配置是否成功
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class HibernateTest {
@Resource(name="sessionFactory")
private SessionFactory sessionFactory;
@Test
public void fun1(){
Configuration conf=new Configuration();
conf.configure();
Session session = conf.buildSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
User user = new User();
user.setUser_code("tom");
user.setUser_name("tom");
user.setUser_password("1234");
session.save(user);
transaction.commit();
session.close();
}
@Test
public void fun2(){
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User user = new User();
user.setUser_code("jack");
user.setUser_name("jack");
user.setUser_password("1234");
session.save(user);
transaction.commit();
session.close();
}
@Test
public void fun3(){
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User user = new User();
user.setUser_code("jock");
user.setUser_name("jock");
user.setUser_password("1234");
session.save(user);
transaction.commit();
session.close();
}
}
添加连接池
创建db.properties
jdbc.jdbcUrl=jdbc:mysql:///jdbctest
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=1234
修改applicationContext
<!-- 读取db.properties文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置c3p0连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
<property name="driverClass" value="${jdbc.driverClass}" ></property>
<property name="user" value="${jdbc.user}" ></property>
<property name="password" value="${jdbc.password}" ></property>
</bean>
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!--将连接池注入sessionFactory,Hibernate会通过连接池获得连接-->
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<!--配置hibernate基本信息-->
<props>
<!--必选配置-->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!--可选配置-->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!--引入orm映射,指定orm元数据所在的包路径,-->
<property name="mappingDirectoryLocations" value="classpath:com/fmt/ssh/domain"></property>
</bean>
使用HibernateDaoSupport
//为HibernateDaoSupport 注入sessionFactory
public class UserServiceImp extends HibernateDaoSupport implements UserService{
@Override
public User getUserByCodePassWord(String pwd) {
// //hql
// return getHibernateTemplate().execute(session -> {
// String hql="from User where user_code=?";
// Query query = session.createQuery(hql);
// query.setParameter(0,pwd);
// User user = (User) query.uniqueResult();
// return user;
// });
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(User.class);
detachedCriteria.add(Restrictions.eq("user_code",pwd));
List<User> criteria = (List<User>) getHibernateTemplate().findByCriteria(detachedCriteria);
if (criteria!=null&&criteria.size()>0){
return criteria.get(0);
}
return null;
}
}
<!--service配置 -->
<bean name="userService" class="com.fmt.ssh.service.UserServiceImp">
<!--注入sessionFactory-->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
事务aop
<!--<!–配置通知–>-->
<!--<tx:advice id="txAdvice" transaction-manager="transactionManager">-->
<!--<tx:attributes>-->
<!--<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" />-->
<!--<tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED"/>-->
<!--<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" />-->
<!--<tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" />-->
<!--<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" />-->
<!--<tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" />-->
<!--<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED"/>-->
<!--<tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" />-->
<!--</tx:attributes>-->
<!--</tx:advice>-->
<!--<!– 配置将通知织入目标对象-->
<!--配置切点-->
<!--配置切面 –>-->
<!--<aop:config>-->
<!--<aop:pointcut expression="execution(* com.fmt.ssh.service.*ServiceImpl.*(..))" id="txPc"/>-->
<!--<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />-->
<!--</aop:config>-->
<!--注解事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
@Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED,readOnly = true)
public class UserServiceImp extends HibernateDaoSupport implements UserService{
}
扩大session作用范围
在web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--让spring随web启动而启动-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置文件位置参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--扩大session作用范围
注意:任何filter一定要在struct2的filter之前
-->
<filter >
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<!--struct2-->
<filter >
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
网友评论