Spring——管理对象的容器
1,环境搭建:
创建web项目。创建类User。
1,导入spring核心包
2,创建配置文件(文件名随意,路径随意)
3,书写配置文件(注册对象到容器)
4,测试
输出不为空即成功。
2,IOC(反转控制)
以前,对象的创建(new)与对象的依赖关系(service与dao)由程序员自己声明。
使用spring之后由容器进行创建管理
DI(依赖注入)
实现IOC思想的技术。
3,bean配置——Scope属性
singleton:(默认值)每个对象在容器中只会存在一个实例,每一次getBean获得的都是同一个对象。
prototype:多例原型,每次获得都会创建,每次创建的都是新的对象。(action)
request
session
4,Spring属性注入
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<!-- set方式注入: -->
<bean name="user" class="cn.itcast.bean.User" >
<!--值类型注入: 为User对象中名为name的属性注入tom作为值 -->
<property name="name" value="tom" ></property>
<property name="age" value="18" ></property>
<!-- 引用类型注入: 为car属性注入下方配置的car对象 -->
<property name="car" ref="car" ></property>
</bean>
<!-- 将car对象配置到容器中 -->
<bean name="car" class="cn.itcast.bean.Car" >
<property name="name" value="兰博基尼" ></property>
<property name="color" value="黄色" ></property>
</bean>
<!-- ============================================================ -->
<!-- 构造函数注入 -->
<bean name="user2" class="cn.itcast.bean.User" >
<!-- name属性: 构造函数的参数名 -->
<!-- index属性: 构造函数的参数索引 -->
<!-- type属性: 构造函数的参数类型-->
<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>
<!-- ============================================================= -->
<!-- p名称空间注入, 走set方法
1.导入P名称空间 xmlns:p="http://www.springframework.org/schema/p"
2.使用p:属性完成注入
|-值类型: p:属性名="值"
|-对象类型: p:属性名-ref="bean名称"
-->
<bean name="user3" class="cn.itcast.bean.User" p:name="jack" p:age="20" p:car-ref="car" >
</bean>
<!-- ============================================================= -->
<!--
spel注入: spring Expression Language sping表达式语言
-->
<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>
<!-- ============================================================= -->
<!-- 复杂类型注入 -->
<bean name="cb" class="cn.itcast.c_injection.CollectionBean" >
<!-- 如果数组中只准备注入一个值(对象),直接使用value|ref即可
<property name="arr" value="tom" ></property>
-->
<!-- array注入,多个元素注入 -->
<property name="arr">
<array>
<value>tom</value>
<value>jerry</value>
<ref bean="user4" />
</array>
</property>
<!-- 如果List中只准备注入一个值(对象),直接使用value|ref即可
<property name="list" value="jack" ></property>-->
<property name="list" >
<list>
<value>jack</value>
<value>rose</value>
<ref bean="user3" />
</list>
</property>
<!-- map类型注入 -->
<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>
<!-- prperties 类型注入 -->
<property name="prop" >
<props>
<prop key="driverClass">com.jdbc.mysql.Driver</prop>
<prop key="userName">root</prop>
<prop key="password">1234</prop>
</props>
</property>
</bean>
</beans>
5,spring注解配置
1,加包
2,引入约束
3,配置文件
<context:component-scan base-package="cn.itcast.bean"></context:component-scan>
4,
//<bean name="user" class="cn.itcast.bean.User" />
//@Component("user")
// @Service("user") // service层
// @Controller("user") // web层
@Repository("user")// dao层
//指定对象的作用范围
@Scope(scopeName="singleton")
public class User {
private String name;
@Value("18")
private Integer age;
//@Autowired //自动装配
//问题:如果匹配多个类型一致的对象.将无法选择具体注入哪一个对象.
//@Qualifier("car2")//使用@Qualifier注解告诉spring容器自动装配哪个名称的对象
@Resource(name="car")//手动注入,指定注入哪个名称的对象
private Car car;
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public String getName() {
return name;
}
@Value("tom")
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@PostConstruct //在对象被创建后调用.init-method
public void init(){
System.out.println("我是初始化方法!");
}
@PreDestroy //在销毁之前调用.destory-method
public void destory(){
System.out.println("我是销毁方法!");
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", car=" + car + "]";
}
}
6,junit整合
1,导包,增加
2,
//帮我们创建容器
@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);
}
@Test
public void fun2(){
System.out.println(u);
}
@Test
public void fun3(){
System.out.println(u);
}
}
7,SpringAOP
1,动态代理
动态代理要求被代理对象必须实现接口。
2,CGLIB代理
第三方代理技术,原理是通过对对象的继承进行代理,即要求类不是final。
Sping的代理是两种代理方式的混合。优先使用动态代理。
1,导包
spring的aop:
spring-aspects-4.2.4.RELEASE.jar
spring-aop-4.2.4.RELEASE.jar
spring需要的第三方aop:
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
2,准备目标对象
public class UserServiceImpl implements UserService {
@Override
public void save() {
System.out.println("保存用户!");
}
@Override
public void delete() {
System.out.println("删除用户!");
}
@Override
public void update() {
System.out.println("更新用户!");
}
@Override
public void find() {
System.out.println("查找用户!");
}
}
3,准备通知
import org.aspectj.lang.ProceedingJoinPoint;
public class MyAdvice {
public void before() {
System.out.println("前置通知");
}
public void after() {
System.out.println("后置通知");
}
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前");
Object proceed = pjp.proceed();
System.out.println("环绕后");
return proceed;
}
}
4,配置进行织入
准备目标对象bean和通知bean,配置切入点。
<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="userServiceTarget" class="conm.example.service.UserServiceImpl"></bean>
<bean name="myAdvice" class="conm.example.aop.MyAdvice"></bean>
<aop:config>
<aop:pointcut expression="execution(* conm.example.service.*ServiceImpl.*(..))" id="pc"/>
<aop:aspect ref="myAdvice">
<aop:before method="before" pointcut-ref="pc"/>
<aop:around method="around" pointcut-ref="pc"/>
<aop:after-returning method="after" pointcut-ref="pc"/>
</aop:aspect>
</aop:config>
</beans>
8,Spring整合jdbc
spring提供了一个jdbctemplate对象封装了jdbc技术。
1,导包
核心4+2,测试包2
com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
spring-jdbc-4.2.4.RELEASE.jar
spring-tx-4.2.4.RELEASE.jar
mysql-connector-java-5.1.7-bin.jar
2,书写dao
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.example.domain.User;
public class UserDaoImpl implements UserDao {
private JdbcTemplate jt;
public void setJt(JdbcTemplate jt) {
this.jt = jt;
}
@Override
public void save(User user) {
String sql = "insert into T_User values(null,?)";
jt.update(sql,user.getName());
}
@Override
public void delete(Integer id) {
String sql = "delete from T_User where id = ?";
jt.update(sql,id);
}
@Override
public void update(User user) {
String sql = "update T_User set name = ? where id = ?";
jt.update(sql,user.getName(),user.getId());
}
@Override
public User getById(Integer id) {
String sql = "select * from T_User where id = ?";
return jt.queryForObject(sql, new RowMapper<User>(){
@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";
return jt.queryForObject(sql, Integer.class);
}
@Override
public List<User> getAll() {
String sql = "select * from T_User";
return jt.query(sql, new RowMapper<User>() {
@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;
}});
}
}
3,配置连接池,jdbc模板,dao的依赖关系。
<?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" 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 ">
<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>
<!-- jdbcTemplate -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- userdao -->
<bean name="userDao" class="com.example.dao.UserDaoImpl">
<property name="jt" ref="jdbcTemplate"></property>
</bean>
</beans>
其中,db.properties为src目录下单独文件:
jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/Spring_03
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
tip:
继承JdbcDaoSupport,可跳过jdbctemplate,直接将数据源配置进dao
<!--数据源-->
<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>
<!-- 2.Dao-->
<bean name="accountDao" class="cn.itcast.dao.AccountDaoImpl" >
<property name="dataSource" ref="dataSource" ></property>
</bean>
9,Spring中的事务
一,事务隔离级别:
1 读未提交
2 读已提交
4 可重复读
8 串行化
二,只读
true | false
三,事务传播行为
重点:PROPAGATION_REQUIRD
提供事务核心管理器,封装了所有事务操作,不用手动写事务,只需配置
spring中管理事务的方式
xml配置(aop)
<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>
<!-- 以方法为单位,指定方法应用什么事务属性
isolation:隔离级别
propagation:传播行为
read-only:是否只读
-->
<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"/>
<!-- 配置切面 : 通知+切点
advice-ref:通知的名称
pointcut-ref:切点的名称
-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
</aop:config>