转载自 http://blog.youkuaiyun.com/wangyang1354/article/details/48198411
Bean的作用范围
.singleton 默认的形式,在Spring的IOC容器中默认情况下只有一个对象的实例。
.prototype 每次从容器中获取的bean都是新的对象。
.request
.response
.global session
1. Spring中Bean(默认的单例模式下)实例化的时间:容器实例化的时候。设置lay-init=“true”的时候会在getBean的时候才会实例化。
2. 如果范围是prototype的时候,实在getBean的时候进行实例化的。
Init-method 当bean被实例化之后会自动执行init-method中的方法。
Destroy-method 当bean被销毁的时候自动执行里面的方法。
基本的原理总结为:
Xml配置文件中定义了很多属性,与之对应的创建一个含有这些类型的属性的类。
通过读取XML中这些属性的值,填入到对应的那个类的属性当中去。
在这个类中完成实例化bean对象,注入对象等操作
依赖注入的两种方式:
1.<bean id = “userDao” name = “userDao” class = “com.siti.entity.UserDaoImpl” />
<bean id = “userService” name = “userService” class = “com.siti.service.UserServiceImpl”>
<property name = “userDao” ref = “userDao”></property>
</bean>
2.使用内部bean的方式,但是这样的话这个bean就不能被其他的bean使用了
<bean id = “userDao” name = “userDao” class = “com.siti.service.UserServiceImpl”>
<property name = “userDao”>
<bean class = “com.siti.entity.UserDaoImpl” />
</property>
</bean>
构造方法注入依赖对象和值
pulic void UserService(UserDao userDao , String name)
{
}
<bean id = “userDao” name = “userDao” class = “com.siti.entity.UserDaoImpl” />
<bean id = “userService” class = “com.siti.serviceimpl.UserServiceImpl”>
<constructor-arg index = “0” type = “com.siti.dao.UserDao” ref = “userDao”/>
<constructor-arg index = “1” type = “nihao”></constructor-arg>
</bean>
@Autowired是spring框架的,但是@Resource集成到了Javaee里面了(不建议使用)
配置文件中写
<context:annotation-config/>
<bean id = “userDao” class = “com.siti.impl.UserDaoImpl”/>
<bean id = “userServiceImpl” class = “com.siti.service.impl.UserServiceImpl’ />
同在UserServiceImpl中属性之前加上@Resource就可以啦
可以加参数@Resource(name = “userDao”)
@Autowired与@Resource使用一样的。
Autowired(required = true) 默认是必须注入的
@Autowired @Qualifier(“userDao”) 按名进行装配
Spring自动扫描
<context:component-scan base-package = “com.siti/>”
在Dao的实现类中标注:@Repository
在service类中@Service(中间可以指定其名称)标注会自动的将对象交给spring进行管理
@Scope指定作用域范围
指定初始化方法:@PostConstruct
指定关闭资源的函数:@PreDestroy
AOP代理对象
基于注解的方式实现
首先启动对@AspectJ注解的支持<aop:aspectj-autoproxy/>以及引入AOP的命名空间http://www............
例如
<?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: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-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<aop:aspectj-autoproxy/>
<bean id="myInterceptor" class="cn.siti.service.MyInterceptor"/>
<bean id="personService" class="cn.siti.service.impl.PersonServiceBean"></bean>
</beans>
@Pointcut(“execution (* cn.siti.service.. * . * (..))”)
Execution表示执行,*表示返回值的类型(*是任何的类型),cn.siti.service表示在哪个包下面进行拦截,后面的两个点表示对于它的子包底下的类也要进行拦截,后面的*表示包下面的类*表示所有类,后面的*表示方法,后面的括号(. . )表示参数随意
@Aspect
public class MyInterceptor {
@Pointcut("execution (* cn.itcast.service.impl.PersonServiceBean.*(..))")
private void anyMethod() {} //声明切入点
@Before("anyMethod() && args(name)")
public void doAccessCheck(String name) {
System.out.println("前置通知:"+ name);
}
@AfterReturning(pointcut="anyMethod()",returning="result")
public void doAfterReturning(String result) {
System.out.println("后置通知:"+ result);
}
@After("anyMethod()")---->最后一定会执行的
public void doAfter() {
System.out.println("最终通知!");
}
@AfterThrowing(pointcut="anyMethod()",throwing="e")
public void doAfterThrowing(Exception e) {
System.out.println("例外通知:"+ e);
}
@Around("anyMethod()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
//if(){//判断用户是不是有权限
System.out.println("环绕通知");
Object result = pjp.proceed();
System.out.println("运行");
//}
return result;
}
使用配置文件配置的方式
<?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: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-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<aop:aspectj-autoproxy/>
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
<bean id="aspetbean" class="cn.itcast.service.MyInterceptor"/>
<aop:config>
<aop:aspect id="asp" ref="aspetbean">
<aop:pointcut id="mycut" expression="execution(* cn.itcast.service..*.*(..))"/>
<aop:before pointcut-ref="mycut" method="doAccessCheck"/>
<aop:after-returning pointcut-ref="mycut" method="doAfterReturning"/>
<aop:after-throwing pointcut-ref="mycut" method="doAfterThrowing"/>
<aop:after pointcut-ref="mycut" method="doAfter"/>
<aop:around pointcut-ref="mycut" method="doBasicProfiling"/>
</aop:aspect>
</aop:config>
</beans>
Spring+JDBC组合开发
配置文件
<?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: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-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="${maxActive}"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}"/>
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"> <property name="dataSource" ref="dataSource"/>
</bean>
</beans>
jdbc.properties
driverClassName=org.gjt.mm.mysql.Driver
url=jdbc\:mysql\://localhost\:3306/itcast?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=123456
initialSize=1
maxActive=500
maxIdle=2
minIdle=1
注解的方式配置事务
Unchecked 运行期例外,事务会回滚的(默认的)
Checked 这种事务不会回滚(默认的方式)
对于checked这种事务要求回滚: @Transactional(rollbackFor = Exception.class)
不需要使用事务的话
@Transactional(propagation = Propagation.NOT_SUPPORTED)
采用基于XML的方式配置事务
建议使用注解的方式使用事务。
整合开发
Spring集成Hibernate二级缓存
<?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: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-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="1"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="500"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="2"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>cn/itcast/bean/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=false
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=false
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
</value>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"/>
<bean id="personList" class="cn.itcast.web.PersonAction"/>
</beans>
Spring 集成JPA
在src目录下创建META-INF文件夹,在下面创建persistentce.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="itcast" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="123456"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
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: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-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="itcast"/>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"/>
<bean name="/person/list" class="cn.itcast.web.action.PersonAction"/>
<bean name="/person/manage" class="cn.itcast.web.action.PersonManageAction"/>
</beans>