Spring学习总结----
一、导入Spring必须的jar包
二、简单示例入门注入一个User
1.编写User实体类
package test.Spring.helloworld;
import java.util.List;
import java.util.Map;
public class User {
@Override
public String toString() {
return “User [id=” + id + “, name=” + name + “]”;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private int id;
private String name;
}
2.编写Spring配置文件,类型为xml,文件名可以自定义
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" ><span style="color: #0000ff;"><</span><span style="color: #800000;">bean </span><span style="color: #ff0000;">id</span><span style="color: #0000ff;">="User"</span><span style="color: #ff0000;"> class</span><span style="color: #0000ff;">="test.Spring.helloworld.User"</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="id"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="1"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="name"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="jayjay"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">bean</span><span style="color: #0000ff;">></span>
</beans>
3.利用Spring容器创建托管对象User
ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml"); User u = (User)context.getBean("User"); System.out.println(u);
三、Bean的配置深入
1.bean引用其他bean
实体类示例:
package test.Spring.helloworld;
public class HelloWorld {
public User getUser() {
return user;
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> setUser(User user) {
</span><span style="color: #0000ff;">this</span>.user =<span style="color: #000000;"> user;
}
@Override
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> String toString() {
</span><span style="color: #0000ff;">return</span> "HelloWorld [name=" + name + ", user=" + user + "]"<span style="color: #000000;">;
}
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> String getName() {
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> name;
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> setName(String name) {
</span><span style="color: #0000ff;">this</span>.name =<span style="color: #000000;"> name;
}
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> String name;
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> User user;
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> HelloWorld(){
}
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> HelloWorld(String name){
</span><span style="color: #0000ff;">this</span>.name =<span style="color: #000000;"> name;
}
}
配置示例:
<!-- reference other bean --> <bean id="HelloWorld" class="test.Spring.helloworld.HelloWorld"> <!-- <property name="name" value="spring1"></property> --> <constructor-arg value="spring2" type="java.lang.String"></constructor-arg> <property name="user"> <ref bean="User"/> </property> </bean>
调用方法依然是根据bean中的id
2.集合bean配置
实体类示例:
package test.Spring.helloworld;
import java.util.List;
import java.util.Map;
public class User {
public Map<String, Integer> getMap() {
return map;
}
public void setMap(Map<String, Integer> map) {
this.map = map;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
@Override
public String toString() {
return “User [id=” + id + “, name=” + name + “, list=” + list
+ “, map=” + map + “]”;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private int id;
private String name;
private List<String> list;
private Map<String,Integer> map;
}
配置示例:
<!-- Configure the list bean --> <bean id="testList" class="test.Spring.helloworld.User"> <property name="list"> <list> <value>list1</value> <value>list2</value> <value>list3</value> </list> </property> </bean><span style="color: #008000;"><!--</span><span style="color: #008000;"> configure the map </span><span style="color: #008000;">--></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">bean </span><span style="color: #ff0000;">id</span><span style="color: #0000ff;">="testMap"</span><span style="color: #ff0000;"> class</span><span style="color: #0000ff;">="test.Spring.helloworld.User"</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="map"</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">map</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">entry </span><span style="color: #ff0000;">key</span><span style="color: #0000ff;">="first"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="1"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">entry</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">entry </span><span style="color: #ff0000;">key</span><span style="color: #0000ff;">="second"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="2"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">entry</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">entry </span><span style="color: #ff0000;">key</span><span style="color: #0000ff;">="third"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="3"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">entry</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">map</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">bean</span><span style="color: #0000ff;">></span></pre>
3.Properties类型的bean
实体类示例:
package test.Spring.helloworld;
import java.util.Properties;
public class DataSource {
@Override
public String toString() {
return “Properties [properties=” + properties + “]”;
}
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> Properties getProperties() {
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> properties;
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> setProperties(Properties properties) {
</span><span style="color: #0000ff;">this</span>.properties =<span style="color: #000000;"> properties;
}
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> Properties properties;
}
配置示例:
<!-- configure the properties --> <bean id="dataSource1" class="test.Spring.helloworld.DataSource"> <property name="properties"> <props> <prop key="user">root</prop> <prop key="password">1234</prop> <prop key="jdbcUrl">jdbc:mysql:///test</prop> <prop key="driverClass">com.mysql.jdbc.Driver</prop> </props> </property> </bean>
4.使用Util定义引用其他bean的公共集合
需要先在xml导入命名空间
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd" xmlns:util="http://www.springframework.org/schema/util" > </beans>
集合以及调用的xml配置
<!-- if properties of collection are beans --> <util:list id="users"> <ref bean="User"/> <ref bean="User"/> <ref bean="User"/> </util:list><span style="color: #0000ff;"><</span><span style="color: #800000;">bean </span><span style="color: #ff0000;">id</span><span style="color: #0000ff;">="Users"</span><span style="color: #ff0000;"> class</span><span style="color: #0000ff;">="test.Spring.helloworld.Users"</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="list"</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">ref </span><span style="color: #ff0000;">bean</span><span style="color: #0000ff;">="users"</span><span style="color: #0000ff;">/></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">bean</span><span style="color: #0000ff;">></span></pre>
5.使用p简化bean的属性赋值
首先,导入p的命名空间
xmlns:p="http://www.springframework.org/schema/p"
实体类实例:
package test.Spring.helloworld;
import java.util.List;
import java.util.Map;
public class User {
@Override
public String toString() {
return “User [id=” + id + “, name=” + name + “]”;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private int id;
private String name;
}
配置示例:
<!-- use p to write the bean quickly and conveniently --> <bean id="User1" class="test.Spring.helloworld.User" p:id="2" p:name="jayjay2" />
6.abstract模板bean
设置abstract=true表明此bean是模板bean,为其他bean提供属性值模板
<!-- template bean --> <bean abstract="true" id="template" p:id="50" p:name="fromTemplate"></bean> <bean id="User2" parent="template" class="test.Spring.helloworld.User"></bean>
7.单例bean和原型bean
<!-- use scope to build singleton/prototype bean --> <bean id="User3" parent="template" scope="singleton" class="test.Spring.helloworld.User"></bean> <bean id="User4" parent="template" scope="prototype" class="test.Spring.helloworld.User"></bean>
singleton:此bean为单例,在context创建时已经创建,并且只有一个实例。
prototype:当需要时创建实例。
8.静态工厂方法配置bean
静态工厂类示例:
package test.Spring.FactoryBean;
import java.util.HashMap;
import java.util.Map;
public class StaticFactoryMethod {
public static Map<String,Person> map = new HashMap<String,Person>();
</span><span style="color: #0000ff;">static</span><span style="color: #000000;"> {
map.put(</span>"first", <span style="color: #0000ff;">new</span> Person(1,"jayjay1"<span style="color: #000000;">));
map.put(</span>"second", <span style="color: #0000ff;">new</span> Person(2,"jayjay2"<span style="color: #000000;">));
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> Person getPerson(String key){
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> map.get(key);
}
}
配置示例:
<!-- static factory method --> <bean id="person" factory-method="getPerson" class="test.Spring.FactoryBean.StaticFactoryMethod"> <constructor-arg value="first" type="java.lang.String"></constructor-arg> </bean>
9.实例工厂方法配置bean
工厂类示例:
package test.Spring.FactoryBean;
import java.util.HashMap;
import java.util.Map;
public class InstanceFactoryMethod {
public static Map<String,Person> map = new HashMap<String,Person>();
</span><span style="color: #0000ff;">static</span><span style="color: #000000;"> {
map.put(</span>"first", <span style="color: #0000ff;">new</span> Person(1,"jayjay1"<span style="color: #000000;">));
map.put(</span>"second", <span style="color: #0000ff;">new</span> Person(2,"jayjay2"<span style="color: #000000;">));
}
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> Person getPerson(String key){
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> map.get(key);
}
}
配置示例:
<!-- instance factory method --> <bean id="InstanceFactoryMethod" class="test.Spring.FactoryBean.InstanceFactoryMethod"></bean> <bean id="person1" factory-bean="InstanceFactoryMethod" factory-method="getPerson"> <constructor-arg value="second"></constructor-arg> </bean>
10.通过实现FactoryBean完成bean的配置
需要对FactoryBean接口的3个方法进行适当重写
PersonFactoryBean类示例:
package test.Spring.FactoryBean;
import org.springframework.beans.factory.FactoryBean;
public class PersonFactoryBean implements FactoryBean<Person>{
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span><span style="color: #000000;"> getId() {
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> id;
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> setId(<span style="color: #0000ff;">int</span><span style="color: #000000;"> id) {
</span><span style="color: #0000ff;">this</span>.id =<span style="color: #000000;"> id;
}
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> String getName() {
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> name;
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> setName(String name) {
</span><span style="color: #0000ff;">this</span>.name =<span style="color: #000000;"> name;
}
</span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">int</span><span style="color: #000000;"> id;
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> String name;
@Override
</span><span style="color: #0000ff;">public</span> Person getObject() <span style="color: #0000ff;">throws</span><span style="color: #000000;"> Exception {
</span><span style="color: #008000;">//</span><span style="color: #008000;"> TODO Auto-generated method stub</span>
<span style="color: #0000ff;">return</span> <span style="color: #0000ff;">new</span><span style="color: #000000;"> Person(id,name);
}
@Override
</span><span style="color: #0000ff;">public</span> Class<?><span style="color: #000000;"> getObjectType() {
</span><span style="color: #008000;">//</span><span style="color: #008000;"> TODO Auto-generated method stub</span>
<span style="color: #0000ff;">return</span> Person.<span style="color: #0000ff;">class</span><span style="color: #000000;">;
}
@Override
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">boolean</span><span style="color: #000000;"> isSingleton() {
</span><span style="color: #008000;">//</span><span style="color: #008000;"> TODO Auto-generated method stub</span>
<span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #000000;">;
}
}
配置示例:
<!-- use factory bean to get a instance --> <bean id="person2" class="test.Spring.FactoryBean.PersonFactoryBean"> <property name="id" value="3"></property> <property name="name" value="FactoryBean"></property> </bean>
四、通过注解配置bean
加上注解的类会被Spring容器管理
@Component
标注于通用实体类
@Controller
标注于Controller/Action
@Service
标注于Service
@Respository
标注于RespositoryImpl/DaoImlp
@Autowired
依据类型自动装配
@Qualifier
指定自动装载的bean的name
1.在Spring配置文件中导入context命名空间,并加入
<context:component-scan base-package="test.Spring.Annotation"></context:component-scan>
表示Spring将扫描test.Spring.Annotation及其子包中所有java文件,并将带有注解的类加入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" 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.xsd" xmlns:context="http://www.springframework.org/schema/context"> <context:component-scan base-package="test.Spring.Annotation"></context:component-scan> </beans>
2.模拟三层,并用Spring注解方式注入
项目结构:
Person实体类
package test.Spring.Annotation; import org.springframework.stereotype.Component;
@Component
public class Person {
@Override
public String toString() {
return “Person [id=” + id + “, name=” + name + “]”;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
</span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">int</span><span style="color: #000000;"> id;
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> String name;
}
PersonController
package test.Spring.Annotation.Controller;
import org.springframework.stereotype.Controller;
@Controller
public class PersonController {
public void excute(){
System.out.println(“PersonController.excute()…”);
}
}
PersonService
package test.Spring.Annotation.Service;
import org.springframework.stereotype.Service;
@Service
public class PersonService {
public void add(){
System.out.println(“PersonService.add()…”);
}
}
PersonRepository接口
package test.Spring.Annotation.Repository;
public interface PersonRepository {
void add();
}
PersonRepositoryImpl接口实现类
package test.Spring.Annotation.Repository;
import org.springframework.stereotype.Repository;
@Repository
public class PersonRepositoryImpl implements PersonRepository {
@Override
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> add() {
System.out.println(</span>"PersonRepositoryImpl.add()..."<span style="color: #000000;">);
}
}
Main类中测试
package test.Spring.Annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import test.Spring.Annotation.Controller.PersonController;
import test.Spring.Annotation.Repository.PersonRepository;
import test.Spring.Annotation.Service.PersonService;
public class Main {
public static void main(String[] args) {
ApplicationContext context =new ClassPathXmlApplicationContext(“applicationContextForAnnotation.xml”);
</span><span style="color: #008000;">//</span><span style="color: #008000;">inject the common bean</span>
System.out.println(context.getBean("testAutowired"<span style="color: #000000;">));
</span><span style="color: #008000;">//</span><span style="color: #008000;">inject the repository</span>
PersonRepository pr = (PersonRepository)context.getBean("personRepositoryImpl"<span style="color: #000000;">);
pr.add();
</span><span style="color: #008000;">//</span><span style="color: #008000;">inject the controller</span>
PersonController pc = (PersonController)context.getBean("personController"<span style="color: #000000;">);
pc.excute();
</span><span style="color: #008000;">//</span><span style="color: #008000;">inject the service</span>
PersonService ps = (PersonService)context.getBean("personService"<span style="color: #000000;">);
ps.add();
}
}
3.泛型三层的注入
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" 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.xsd " xmlns:context="http://www.springframework.org/schema/context" > <context:component-scan base-package="test.Spring.Generic.di"></context:component-scan> </beans>
BaseRespository
package test.Spring.Generic.di;
public class BaseRepository<T> {
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> save() {
System.out.println(</span>"repository.save()..."<span style="color: #000000;">);
}
}
PersonRepository
package test.Spring.Generic.di;
public interface PersonRespository {
void save();
}
PersonRepositoryImpl
继承BaseRepository就不需要再写一次save方法,且同时实现了PersonRepository接口
package test.Spring.Generic.di;
import org.springframework.stereotype.Repository;
import test.Spring.Annotation.Person;
@Repository
public class PersonRespositoryImpl extends BaseRepository<Person> implements PersonRespository {
}
BaseService对Dao进行自动装配,子类继承后装配的是子类Respository
package test.Spring.Generic.di;
import org.springframework.beans.factory.annotation.Autowired;
public class BaseService<T> {
@Autowired
</span><span style="color: #0000ff;">protected</span> BaseRepository<T><span style="color: #000000;"> baseRespository;
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> save(){
System.out.println(</span>"service.save()..."<span style="color: #000000;">);
System.out.println(baseRespository);
}
}
PersonService继承了BaseService,就不需要再写实现save方法,定义Repository字段了
package test.Spring.Generic.di;
import org.springframework.stereotype.Service;
import test.Spring.Annotation.Person;
@Service
public class PersonService extends BaseService<Person>{
}
Main类中调用
package test.Spring.Generic.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context =new ClassPathXmlApplicationContext(“applicationContextForGeneric.xml”);
PersonService ps = (PersonService)context.getBean(“personService”);
ps.save();
}
}
输出为
第二句说明调用的是继承BaseService的PersonService拿到的Respository是PersonRepositoryImpl,说明泛型注入成功。
十、使用SpringAOP完成简单的程序
1.导入SpringAOP所需jar包
2.编写spring的配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation</span><span style="color: #0000ff;">="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "</span><span style="color: #ff0000;"> xmlns:util</span><span style="color: #0000ff;">="http://www.springframework.org/schema/util"</span><span style="color: #ff0000;"> xmlns:p</span><span style="color: #0000ff;">="http://www.springframework.org/schema/p"</span><span style="color: #ff0000;"> xmlns:context</span><span style="color: #0000ff;">="http://www.springframework.org/schema/context"</span><span style="color: #ff0000;"> xmlns:aop</span><span style="color: #0000ff;">="http://www.springframework.org/schema/aop"</span> <span style="color: #0000ff;">></span> <span style="color: #008000;"><!--</span><span style="color: #008000;"> configure the package for spring to scan </span><span style="color: #008000;">--></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">context:component-scan </span><span style="color: #ff0000;">base-package</span><span style="color: #0000ff;">="test.Spring.AOP"</span> <span style="color: #0000ff;">/></span> <span style="color: #008000;"><!--</span><span style="color: #008000;"> make the aspectj annotation to be used </span><span style="color: #008000;">--></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">aop:aspectj-autoproxy</span><span style="color: #0000ff;">></</span><span style="color: #800000;">aop:aspectj-autoproxy</span><span style="color: #0000ff;">></span>
</beans>
3.创建一个HelloWord接口以及它的实现类HelloWordImpl
public interface HelloWord { public int sayHello(int num); }
@Component public class HelloWordImpl implements HelloWord{ public int sayHello(int num){ System.out.println("hello word"); return 100/num; } }
4.SpringAOP注释的类型有5种
@Before 前置通知 在方法执行前执行
@After 后置通知 在方法执行后执行
@AfterThrowing 异常通知 在方法抛出异常之后执行
@AfterReturning 返回通知 在方法返回结果之后执行
@Around 环绕通知 环绕着方法执行
5.创建一个切面类(包含@Before @After @AfterThrowing @AfterReturning)
@Component @Aspect public class HelloWordAspect {@Before(value</span>="execution(* test.Spring.AOP.HelloWord.sayHello(..))"<span style="color: #000000;">) </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> beforeMethod(JoinPoint jp){ String methodName </span>=<span style="color: #000000;"> jp.getSignature().getName(); System.out.println(methodName); System.out.println(</span>"before method execute,args are "+<span style="color: #000000;">Arrays.toString(jp.getArgs())); } @After(</span>"execution(* test.Spring.AOP.HelloWord.sayHello(..))"<span style="color: #000000;">) </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> afterMethod(JoinPoint jp){ System.out.println(</span>"after method execute,args are "+<span style="color: #000000;">Arrays.toString(jp.getArgs())); } @AfterThrowing(value</span>="execution(* test.Spring.AOP.HelloWord.sayHello(..))",throwing="ex"<span style="color: #000000;">) </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> afterThrow(Exception ex){ System.out.println(</span>"afterThrow"+<span style="color: #000000;">ex.getMessage()); } @AfterReturning(value</span>="execution(* test.Spring.AOP.HelloWord.sayHello(..))",returning="result"<span style="color: #000000;">) </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> afterReturn(Object result){ System.out.println(</span>"the result is "+<span style="color: #000000;">result); }
}
6.在主函数调用
public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContextForAOP.xml");HelloWord hw </span>= (HelloWord) context.getBean("helloWordImpl"<span style="color: #000000;">); hw.sayHello(</span>10<span style="color: #000000;">); }
}
7.调用结果
结果说明,在sayHello方法是被Spring代理执行了,执行前后加上了一些切面类中定义的信息。
8.使用Around环绕通知切面类实现类似效果
@Component @Aspect public class HelloWordAspectAround { @Around(value="execution(* test.Spring.AOP.HelloWord.sayHello(..)))") public Object aroundMethod(ProceedingJoinPoint pjp){ Object result = null; String methodName = pjp.getSignature().getName(); try { result = pjp.proceed(); System.out.println("the result is "+result); } catch (Throwable e) { System.out.println("Exception occurs : "+e.getMessage()); throw new RuntimeException(e); } System.out.println(methodName+" end");</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> result; }
}
十一、SpringAOP整合Hibernate并使用事务(模拟买书的过程)
1.内容准备
①.编写实体类
Book
public class Book { public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } private int id; private String name; private int price; private int count; }
Customer
public class Customer { public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } private int id; private String name; private int balance; }
②.编写实体类映射文件
<hibernate-mapping package="springaop.model"> <class name="Book" table="t_book"> <id name="id" type="int" column="id" > <generator class="native"></generator> </id> <property name="name" type="string" column="name"/> <property name="price" type="int" column="price"/> <property name="count" type="int" column="count"/><span style="color: #0000ff;"></</span><span style="color: #800000;">class</span><span style="color: #0000ff;">></span>
</hibernate-mapping>
<hibernate-mapping package="springaop.model"> <class name="Customer" table="t_customer"> <id name="id" type="int" column="id" > <generator class="native"></generator> </id> <property name="name" type="string" column="name"/> <property name="balance" type="int" column="balance"/><span style="color: #0000ff;"></</span><span style="color: #800000;">class</span><span style="color: #0000ff;">></span>
</hibernate-mapping>
③.编写dao及daoImpl
public interface ShopRepository { public int findBookPriceByBookName(String name); public void updateBookCount(String name); public void updateUserBalance(String name,int price); }
@Repository public class ShopRepositoryImpl implements ShopRepository{@Autowired </span><span style="color: #0000ff;">private</span><span style="color: #000000;"> SessionFactory sessionFactory; </span><span style="color: #0000ff;">private</span><span style="color: #000000;"> Session getSession(){ </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> sessionFactory.getCurrentSession(); } @Override </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span><span style="color: #000000;"> findBookPriceByBookName(String name) { String sql </span>= "select b.price from Book b where b.name=?"<span style="color: #000000;">; Query query </span>= getSession().createQuery(sql).setString(0<span style="color: #000000;">, name); </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> (Integer)query.uniqueResult(); } @Override </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> updateBookCount(String name) { String sql1 </span>= "select b.count from Book b where b.name=?"<span style="color: #000000;">; Query query </span>= getSession().createQuery(sql1).setString(0<span style="color: #000000;">,name); </span><span style="color: #0000ff;">int</span> count = (<span style="color: #0000ff;">int</span><span style="color: #000000;">)query.uniqueResult(); </span><span style="color: #0000ff;">if</span>(count<=0<span style="color: #000000;">){ </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> RuntimeException("库存不足"<span style="color: #000000;">); } String sql2 </span>= "update Book b set b.count=b.count-1 where b.name=?"<span style="color: #000000;">; getSession().createQuery(sql2).setString(</span>0<span style="color: #000000;">,name).executeUpdate(); } @Override </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> updateUserBalance(String name, <span style="color: #0000ff;">int</span><span style="color: #000000;"> price) { String sql1 </span>= "select c.balance from Customer c where c.name=?"<span style="color: #000000;">; Query query </span>= getSession().createQuery(sql1).setString(0<span style="color: #000000;">,name); </span><span style="color: #0000ff;">int</span> count = (<span style="color: #0000ff;">int</span><span style="color: #000000;">)query.uniqueResult(); </span><span style="color: #0000ff;">if</span>(count-price<0<span style="color: #000000;">){ </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> RuntimeException("余额不足"<span style="color: #000000;">); } String sql2 </span>= "update Customer c set c.balance=c.balance-? where c.name=?"<span style="color: #000000;">; getSession().createQuery(sql2).setInteger(</span>0, price).setString(1<span style="color: #000000;">,name).executeUpdate(); }
}
④.编写service及serviceImpl
public interface ShopService { public void shop(String bookName,String username); }
@Service public class ShopServiceImpl implements ShopService{@Autowired </span><span style="color: #0000ff;">private</span><span style="color: #000000;"> ShopRepository sr; @Override </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> shop(String bookName, String username) { </span><span style="color: #0000ff;">int</span> price =<span style="color: #000000;"> sr.findBookPriceByBookName(bookName); sr.updateUserBalance(username, price); sr.updateBookCount(bookName); }
}
2.加入Hibernate
①.添加hibernate必须的jar包
②.添加hibernate.cfg.xml
<hibernate-configuration> <session-factory> <!-- 配置hibernate的基本属性 --> <!-- 1.数据源的配置,配置到SpringIOC中,此处不需要再进行配置 --> <!-- 2.关联实体的映射文件 .hbm.xml文件也在IOC容器配置SessionFactory实例时配置 --> <!-- 3.配置hibernate的基本属性 方言、sql显示及格式化、数据库表生成策略、二级缓存--> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property><span style="color: #008000;"><!--</span><span style="color: #008000;"> 配置hibernate二级缓存相关 </span><span style="color: #008000;">--></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">session-factory</span><span style="color: #0000ff;">></span>
</hibernate-configuration>
3.加入Spring
①.导入Spring必须的jar包
②.配置Spring的applicationContext.xml及db.properties文件
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd " xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" ><span style="color: #008000;"><!--</span><span style="color: #008000;"> 配置Spring扫描的包 </span><span style="color: #008000;">--></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">context:component-scan </span><span style="color: #ff0000;">base-package</span><span style="color: #0000ff;">="springaop"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">context:component-scan</span><span style="color: #0000ff;">></span> <span style="color: #008000;"><!--</span><span style="color: #008000;"> 配置数据源 </span><span style="color: #008000;">--></span> <span style="color: #008000;"><!--</span><span style="color: #008000;"> 导入资源文件 </span><span style="color: #008000;">--></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">context:property-placeholder </span><span style="color: #ff0000;">location</span><span style="color: #0000ff;">="classpath:db.properties"</span><span style="color: #0000ff;">/></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">bean </span><span style="color: #ff0000;">id</span><span style="color: #0000ff;">="dataSource"</span><span style="color: #ff0000;"> class</span><span style="color: #0000ff;">="com.mchange.v2.c3p0.ComboPooledDataSource"</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="user"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="${jdbc.user}"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="password"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="${jdbc.password}"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="driverClass"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="${jdbc.driverClass}"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="jdbcUrl"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="${jdbc.jdbcUrl}"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="initialPoolSize"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="${jdbc.initialPoolSize}"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="maxPoolSize"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="${jdbc.maxPoolSize}"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">bean</span><span style="color: #0000ff;">></span> <span style="color: #008000;"><!--</span><span style="color: #008000;"> 配置Hibernete的SessionFactory实例 </span><span style="color: #008000;">--></span> <span style="color: #008000;"><!--</span><span style="color: #008000;"> 通过配置Spring提供的LcalSessionFactory </span><span style="color: #008000;">--></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">bean </span><span style="color: #ff0000;">id</span><span style="color: #0000ff;">="sessionFactory"</span><span style="color: #ff0000;"> class</span><span style="color: #0000ff;">="org.springframework.orm.hibernate4.LocalSessionFactoryBean"</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="dataSource"</span><span style="color: #ff0000;"> ref</span><span style="color: #0000ff;">="dataSource"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="configLocation"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="classpath:hibernate.cfg.xml"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="mappingLocations"</span><span style="color: #ff0000;"> value</span><span style="color: #0000ff;">="classpath:springaop/model/*.hbm.xml"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">bean</span><span style="color: #0000ff;">></span> <span style="color: #008000;"><!--</span><span style="color: #008000;"> 配置Spring的声明式事务 </span><span style="color: #008000;">--></span> <span style="color: #008000;"><!--</span><span style="color: #008000;"> 1.配置事务管理器 </span><span style="color: #008000;">--></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">bean </span><span style="color: #ff0000;">id</span><span style="color: #0000ff;">="transactionManager"</span><span style="color: #ff0000;"> class</span><span style="color: #0000ff;">="org.springframework.orm.hibernate4.HibernateTransactionManager"</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">property </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="sessionFactory"</span><span style="color: #ff0000;"> ref</span><span style="color: #0000ff;">="sessionFactory"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">property</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">bean</span><span style="color: #0000ff;">></span> <span style="color: #008000;"><!--</span><span style="color: #008000;"> 2.配置事务属性 </span><span style="color: #008000;">--></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">tx:advice </span><span style="color: #ff0000;">id</span><span style="color: #0000ff;">="txAdvice"</span><span style="color: #ff0000;"> transaction-manager</span><span style="color: #0000ff;">="transactionManager"</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">tx:attributes</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">tx:method </span><span style="color: #ff0000;">name</span><span style="color: #0000ff;">="*"</span><span style="color: #0000ff;">/></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">tx:attributes</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">tx:advice</span><span style="color: #0000ff;">></span> <span style="color: #008000;"><!--</span><span style="color: #008000;"> 3.配置事务切点,并把切点和事务关联起来, </span><span style="color: #008000;">--></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">aop:config</span><span style="color: #0000ff;">></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">aop:pointcut </span><span style="color: #ff0000;">expression</span><span style="color: #0000ff;">="execution(* springaop.service.*.*(..))"</span><span style="color: #ff0000;"> id</span><span style="color: #0000ff;">="txPointcut"</span><span style="color: #0000ff;">/></span> <span style="color: #0000ff;"><</span><span style="color: #800000;">aop:advisor </span><span style="color: #ff0000;">advice-ref</span><span style="color: #0000ff;">="txAdvice"</span><span style="color: #ff0000;"> pointcut-ref</span><span style="color: #0000ff;">="txPointcut"</span><span style="color: #0000ff;">/></span> <span style="color: #0000ff;"></</span><span style="color: #800000;">aop:config</span><span style="color: #0000ff;">></span>
</beans>
jdbc.user=root jdbc.password=1234 jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql:///test
jdbc.initialPoolSize=5
jdbc.maxPoolSize=10
4.运行测试
public class test { private ApplicationContext context = null;</span><span style="color: #0000ff;">private</span> ShopService ss = <span style="color: #0000ff;">null</span><span style="color: #000000;">; { context </span>= <span style="color: #0000ff;">new</span> ClassPathXmlApplicationContext("applicationContext.xml"<span style="color: #000000;">); ss</span>= context.getBean(ShopService.<span style="color: #0000ff;">class</span><span style="color: #000000;">); } @Test </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> test() <span style="color: #0000ff;">throws</span><span style="color: #000000;"> SQLException{ DataSource ds </span>= context.getBean(DataSource.<span style="color: #0000ff;">class</span><span style="color: #000000;">); System.out.println(ds.getConnection()); } @Test </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> test1(){ ss.shop(</span>"Java", "jayjay"<span style="color: #000000;">); } @Test </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> test3(){ ss.shop(</span>"C", "jayjay"<span style="color: #000000;">); }
}
当钱不够的时候,会抛出异常“余额不足”,并且事务回滚;当钱足够时,正常执行。
源码下载:SpringAOP整合Hibernate并使用事务(模拟买书的过程)-源码
转自:Spring详细教程