三层架构中spring位置,连接三层。
com.springsource.org.apache.log4j-1.2.15.jar(可选,老版本可能需要这个包)
位置任意(建议放到src下),配置文件名任意(建议applicationContext.xml)
IoC – Inverse of Control,控制反转,将对象的创建权反转给Spring!!
以前的对象都是开发人员手动创建和维护,包括依赖关系也是自己注入。
DI – Dependency Injection,依赖注入。
实现 IOC 思想需要 DI 做支持。
在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件中。
ApplicationContext接口
BeanFactory工厂(是Spring框架早期的创建Bean对象的工厂接口)
BeanFactory – BeanFactory采取延迟加载,第一次getBean时才会初始化Bean
ApplicationContext – 在加载applicationContext.xml时候就会创建具体的Bean对象的实例,还提供了一些其他的功能。
web开发中,使用applicationContext. 在资源匮乏的环境可以使用BeanFactory.
<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 ">
<bean name="user" class="cn.itcast.bean.User" >bean>
beans>
init-method
配置一个方法作为生命周期初始化方法.spring会在对象创建之后立即调用.
destory-method
配置一个方法作为生命周期的销毁方法.spring容器在关闭并销毁所有容器中的对象之前调用.
空参构造方式
静态工厂(了解)
实例工厂(了解)
<bean name="user" class="cn.itcast.bean.User" >
<property name="name" value="tom" >property>
<property name="age" value="18" >property>
<property name="car" ref="car" >property>
bean>
<bean name="car" class="cn.itcast.bean.Car" >
<property name="name" value="兰博基尼" >property>
<property name="color" value="黄色" >property>
bean>
public class User {
private String name;
private Integer age;
private Car car;
public User(String name, Car car) {
System.out.println("User(String name, Car car)!!");
this.name = name;
this.car = car;
}
。。。
}
<bean name="user2" class="cn.itcast.bean.User" >
<constructor-arg name="name" index="0" type="java.lang.Integer" value="999" >constructor-arg>
<constructor-arg name="car" ref="car" index="1" >constructor-arg>
bean>
<bean name="user3" class="cn.itcast.bean.User" p:name="jack" p:age="20" p:car-ref="car" >
bean>
<bean name="user4" class="cn.itcast.bean.User" >
<property name="name" value="#{user.name}" >property>
<property name="age" value="#{user3.age}" >property>
<property name="car" ref="car" >property>
bean>
<property name="arr">
<array>
<value>tomvalue>
<value>jerryvalue>
<ref bean="user4" />
array>
property>
<property name="list" >
<list>
<value>jackvalue>
<value>rosevalue>
<ref bean="user3" />
list>
property>
<property name="map" >
<map>
<entry key="url" value="jdbc:mysql:///crm" >entry>
<entry key="user" value-ref="user4" >entry>
<entry key-ref="user3" value-ref="user2" >entry>
map>
property>
<property name="prop" >
<props>
<prop key="driverClass">com.jdbc.mysql.Driverprop>
<prop key="userName">rootprop>
<prop key="password">1234prop>
props>
property>
导包4+2+spring-aop
// = @Component("user")
//@Component("user") //早期使用
//@Service("user") // service层
//@Controller("user") // web层
//@Repository("user")// dao层
public class User {
private String name;
private Integer age;
private Car car;
public Car getCar() {
return car;
}
//指定对象的作用范围
@Scope(scopeName="singleton")
public class User {
通过反射的Field赋值,破坏了封装性
@Value("18")
private Integer age;
通过set方法赋值,推荐使用.
@Value("tom")
public void setName(String name) {
this.name = name;
}
@Autowired //自动装配
private Car car;
默认找同名的装配上
@Autowired //自动装配
//问题:如果匹配多个类型一致的对象.将无法选择具体注入哪一个对象.
@Qualifier("car2")//使用@Qualifier注解告诉spring容器自动装配哪个名称的对象
private Car car;
当多个对象是同一个类,需要指定某个对象,@Autowired + @Qualifier()
@Resource(name="car")//手动注入,指定注入哪个名称的对象
private Car car;
当多个对象是同一个类,需要指定某个对象,@Resource()
@Repository("user")
public class User {
private String name;
@Value("18")
private Integer age;
... ...
@PostConstruct //在对象被创建后调用.init-method
public void init(){
System.out.println("我是初始化方法!");
}
@PreDestroy //在销毁之前调用.destory-method
public void destory(){
System.out.println("我是销毁方法!");
}
}
配置注解
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器时使用哪个配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
//将名为user的对象注入到u变量中
@Resource(name="user")
private User u;
@Test
public void fun1(){
System.out.println(u);
}
}
准备目标对象
public class UserServiceImpl implements UserService {
@Override
public void save() {
System.out.println("保存用户!");
//int i = 1/0;
}
@Override
public void delete() {
System.out.println("删除用户!");
}
@Override
public void update() {
System.out.println("更新用户!");
}
@Override
public void find() {
System.out.println("查找用户!");
}
}
准备通知
//通知类
public class MyAdvice {
//前置通知
// |-目标方法运行之前调用
//后置通知(如果出现异常不会调用)
// |-在目标方法运行之后调用
//环绕通知
// |-在目标方法之前和之后都调用
//异常拦截通知
// |-如果出现异常,就会调用
//后置通知(无论是否出现 异常都会调用)
// |-在目标方法运行之后调用
//----------------------------------------------------------------
//前置通知
public void before(){
System.out.println("这是前置通知!!");
}
//后置通知
public void afterReturning(){
System.out.println("这是后置通知(如果出现异常不会调用)!!");
}
//环绕通知
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("这是环绕通知之前的部分!!");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("这是环绕通知之后的部分!!");
return proceed;
}
//异常通知
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-4.2.xsd ">
<bean name="userService" class="cn.itcast.service.UserServiceImpl" >bean>
<bean name="myAdvice" class="cn.itcast.d_springaop.MyAdvice" >bean>
<aop:config>
<aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="pc"/>
<aop:aspect ref="myAdvice" >
<aop:before method="before" pointcut-ref="pc" />
<aop:after-returning method="afterReturning" pointcut-ref="pc" />
<aop:around method="around" pointcut-ref="pc" />
<aop:after-throwing method="afterException" pointcut-ref="pc"/>
<aop:after method="after" pointcut-ref="pc"/>
aop:aspect>
aop:config>
beans>
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:cn/itcast/d_springaop/applicationContext.xml")
public class Demo {
@Resource(name="userService")
private UserService us;
@Test
public void fun1(){
us.save();
}
}
导包4+2
准备目标对象
public class UserServiceImpl implements UserService {
@Override
public void save() {
System.out.println("保存用户!");
//int i = 1/0;
}
@Override
public void delete() {
System.out.println("删除用户!");
}
@Override
public void update() {
System.out.println("更新用户!");
}
@Override
public void find() {
System.out.println("查找用户!");
}
}
准备通知
//通知类
@Aspect
//表示该类是一个通知类
public class MyAdvice {
//抽取出来,同一管理,也可以在下面每个注解中复制一遍。
@Pointcut("execution(* cn.itcast.service.*ServiceImpl.*(..))")
public void pc(){}
//前置通知
//指定该方法是前置通知,并制定切入点
@Before("MyAdvice.pc()")
public void before(){
System.out.println("这是前置通知!!");
}
//后置通知
@AfterReturning("execution(* cn.itcast.service.*ServiceImpl.*(..))")
public void afterReturning(){
System.out.println("这是后置通知(如果出现异常不会调用)!!");
}
//环绕通知
@Around("execution(* cn.itcast.service.*ServiceImpl.*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("这是环绕通知之前的部分!!");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("这是环绕通知之后的部分!!");
return proceed;
}
//异常通知
@AfterThrowing("execution(* cn.itcast.service.*ServiceImpl.*(..))")
public void afterException(){
System.out.println("出事啦!出现异常了!!");
}
//后置通知
@After("execution(* cn.itcast.service.*ServiceImpl.*(..))")
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-4.2.xsd ">
<bean name="userService" class="cn.itcast.service.UserServiceImpl" >bean>
<bean name="myAdvice" class="cn.itcast.e_annotationaop.MyAdvice" >bean>
<aop:aspectj-autoproxy>aop:aspectj-autoproxy>
beans>
spring提供了很多模板整合Dao技术
spring中提供了一个可以操作数据库的对象.对象封装了jdbc技术.
JDBCTemplate => JDBC模板对象
与DBUtils中的QueryRunner非常相似.
导包
准备数据库
书写Dao
public interface UserDao {
//增
void save(User u);
//删
void delete(Integer id);
//改
void update(User u);
//查询单个对象
User getById(Integer id);
//查询值类型
int getTotalCount();
//查询list集合类型
List getAll();
}
//使用JDBC模板实现增删改查
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate;
@Override
public void save(User u) {
String sql = "insert into t_user values(null,?) ";
jdbcTemplate.update(sql, u.getName());
}
@Override
public void delete(Integer id) {
String sql = "delete from t_user where id = ? ";
jdbcTemplate.update(sql,id);
}
@Override
public void update(User u) {
String sql = "update t_user set name = ? where id=? ";
jdbcTemplate.update(sql, u.getName(),u.getId());
}
@Override
public User getById(Integer id) {
String sql = "select * from t_user where id = ? ";
return jdbcTemplate.queryForObject(sql,new RowMapper(){
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
return u;
}}, id);
}
@Override
public int getTotalCount() {
String sql = "select count(*) from t_user ";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
@Override
public List getAll() {
String sql = "select * from t_user ";
List list = jdbcTemplate.query(sql, new RowMapper(){
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
return u;
}});
return list;
}
}
spring配置
db.properties
jdbc.jdbcUrl=jdbc:mysql:///hibernate_32
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=1234
applicationContext.xml
<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:property-placeholder location="classpath:db.properties" />
<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="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<property name="dataSource" ref="dataSource" >property>
bean>
<bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
<property name="jt" ref="jdbcTemplate" >property>
bean>
beans>
测试
//演示JDBC模板
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
@Resource(name="userDao")
private UserDao ud;
@Test
public void fun1() throws Exception{
//0 准备连接池
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///hibernate_32");
dataSource.setUser("root");
dataSource.setPassword("1234");
//1 创建JDBC模板对象
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(dataSource);
//2 书写sql,并执行
String sql = "insert into t_user values(null,'rose') ";
jt.update(sql);
}
@Test
public void fun2() throws Exception{
User u = new User();
u.setName("tom");
ud.save(u);
}
@Test
public void fun3() throws Exception{
User u = new User();
u.setId(2);
u.setName("jack");
ud.update(u);
}
@Test
public void fun4() throws Exception{
ud.delete(2);
}
@Test
public void fun5() throws Exception{
System.out.println(ud.getTotalCount());
}
@Test
public void fun6() throws Exception{
System.out.println(ud.getById(1));
}
@Test
public void fun7() throws Exception{
System.out.println(ud.getAll());
}
}
使用:extends JdbcDaoSupport
//使用JDBC模板实现增删改查
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
@Override
public void save(User u) {
String sql = "insert into t_user values(null,?) ";
super.getJdbcTemplate().update(sql, u.getName());
}
@Override
public void delete(Integer id) {
String sql = "delete from t_user where id = ? ";
super.getJdbcTemplate().update(sql,id);
}
@Override
public void update(User u) {
String sql = "update t_user set name = ? where id=? ";
super.getJdbcTemplate().update(sql, u.getName(),u.getId());
}
@Override
public User getById(Integer id) {
String sql = "select * from t_user where id = ? ";
return super.getJdbcTemplate().queryForObject(sql,new RowMapper(){
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
return u;
}}, id);
}
@Override
public int getTotalCount() {
String sql = "select count(*) from t_user ";
Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
return count;
}
@Override
public List getAll() {
String sql = "select * from t_user ";
List list = super.getJdbcTemplate().query(sql, new RowMapper(){
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
return u;
}});
return list;
}
}
不用将JDBCTemplate放入spring容器
<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:property-placeholder location="classpath:db.properties" />
<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="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
<property name="dataSource" ref="dataSource" >property>
bean>
beans>
事务操作对象
PlatformTransactionManager 接口
注意:在spring中玩事务管理.最为核心的对象就是TransactionManager对象
spring管理事务的属性介绍
将核心事务管理器配置到spring容器
配置TransactionTemplate模板
将事务模板注入Service
在Service中调用模板
这样每个事务的方法都要写这个方法(麻烦),了解即可,一般不用这种方式。
导包
基本配置
配置通知 和 配置将通知织入目标
<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 ">
<context:property-placeholder location="classpath:db.properties" />
<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>
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
tx:attributes>
tx:advice>
<aop:config >
<aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="txPc"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
aop:config>
<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="accountDao" class="cn.itcast.dao.AccountDaoImpl" >
<property name="dataSource" ref="dataSource" >property>
bean>
<bean name="accountService" class="cn.itcast.service.AccountServiceImpl" >
<property name="ad" ref="accountDao" >property>
<property name="tt" ref="transactionTemplate" >property>
bean>
beans>
测试异常操作数据库,数据库数据没有变化。
导包
导入新的约束(tx)
开启注解管理事务
<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 ">
<context:property-placeholder location="classpath:db.properties" />
<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>
<tx:annotation-driven/>
<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="accountDao" class="cn.itcast.dao.AccountDaoImpl" >
<property name="dataSource" ref="dataSource" >property>
bean>
<bean name="accountService" class="cn.itcast.service.AccountServiceImpl" >
<property name="ad" ref="accountDao" >property>
<property name="tt" ref="transactionTemplate" >property>
bean>
beans>
使用注解
在类上和方法上都可以添加事务注解,方法上的注解可以覆盖类上的注解。
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
public class AccountServiceImpl implements AccountService {
private AccountDao ad ;
private TransactionTemplate tt;
@Override
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public void transfer(final Integer from,final Integer to,final Double money) {
//减钱
ad.decreaseMoney(from, money);
int i = 1/0;
//加钱
ad.increaseMoney(to, money);
}
public void setAd(AccountDao ad) {
this.ad = ad;
}
public void setTt(TransactionTemplate tt) {
this.tt = tt;
}
}