Spring

//导入commons-logging-1.1.3.jar、spring-beans-4.1.6.RELEASE.jar、spring-context-4.1.6.RELEASE.jar、
//spring-core-4.1.6.RELEASE.jar、spring-expression-4.1.6.RELEASE.jar
//src下 创建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="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
		<bean id="Hello" class="beans.Hello">
			<property name="name" value="Spring"/>
		</bean>
		<!-- 根据参数位置设置 -->
		<bean id="Student1" class="beans.Student">
			<constructor-arg value="s1" index="0" />
			<constructor-arg value="1" index="1" />
			<constructor-arg value="男" index="2" />
		</bean>
		<!-- 根据参数类型设置 -->
		<!-- 可以使用<![CDATA[<shabi>]]>来设置特殊字符 -->
		<!-- 可以用<value>子节点 -->
		<bean id="Student2" class="beans.Student">
			<constructor-arg type="java.lang.String" >
				<value><![CDATA[<shabi>]]></value>
			</constructor-arg>
			<constructor-arg value="1" type="Integer" />
			<constructor-arg ref="Hello" type="Hello" />
			<!-- 可以修改 -->
			<property name="Hello.name" value="Struct" />
		</bean>
	</beans>
//Hello
	public class Hello {
		private String name;
		public void setName(String name) {
			this.name = name;
		}
		public void hello(){
			System.out.println("name:" + name);
		}
		@Override
		public String toString() {
			return "Hello [name=" + name + "]";
		}
	}
//Student
	public class Student {
		private String name;
		private Integer age;
		private String sex;
		private Hello hello;
		
		public Hello getHello() {
			return hello;
		}
		public void setHello(Hello hello) {
			this.hello = hello;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Integer getAge() {
			return age;
		}
		public void setAge(Integer age) {
			this.age = age;
		}
		public String getSex() {
			return sex;
		}
		public void setSex(String sex) {
			this.sex = sex;
		}
		public Student(String name, Integer age) {
			super();
			this.name = name;
			this.age = age;
		}
		public Student() {
			super();
		}
		public Student(String name, Integer age, String sex) {
			super();
			this.name = name;
			this.age = age;
			this.sex = sex;
		}
		
		public Student(String name, Integer age, Hello hello) {
			super();
			this.name = name;
			this.age = age;
			this.hello = hello;
		}
		@Override
		public String toString() {
			return "Student [name=" + name + ", age=" + age + ", sex=" + sex
					+ ", hello=" + hello.toString() + "]";
		}
	}
//Testspring
	public class Testspring {
		public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			//Hello hello = (Hello) ctx.getBean("Hello");
			//Student student = (Student) ctx.getBean("Student1");
			Student student = (Student) ctx.getBean("Student2");
			System.out.println(student);
		}
	}
//list集合属性
	//Clazz
	public class Clazz {
		public String numble;
		public List<Student> students;
		public String getNumble() {
			return numble;
		}
		public void setNumble(String numble) {
			this.numble = numble;
		}
		public List<Student> getStudents() {
			return students;
		}
		public void setStudents(List<Student> students) {
			this.students = students;
		}
		@Override
		public String toString() {
			return "clazz [numble=" + numble + ", students=" + students + "]";
		}
	}
	//Student
	public class Student {
		private String name;
		
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Student() {
			super();
		}
		public Student(String name) {
			super();
			this.name = name;
		}
		@Override
		public String toString() {
			return "Student [name=" + name + "]";
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Clazz clazz = (Clazz) ctx.getBean("clazz");
			System.out.println(clazz);
		}
	}
	//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="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
		<bean id="student1" class="beans.Student">
			<property name="name" value="student1"/>
		</bean>
		<bean id="student2" class="beans.Student">
			<property name="name" value="student2"/>
		</bean>
		<bean id="clazz" class="beans.Clazz">
			<property name="numble" value="1" />
			<property name="students">
				<list>
					<ref bean="student1"/>
					<ref bean="student2"/>
						<bean id="student3" class="beans.Student">
							<property name="name" value="student3"/>
						</bean>
				</list>
			</property>
		</bean>
	</beans>
//Map集合属性	
	//Clazz
	public class Clazz {
		public String numble;
		private Map<String, Student> students;
		public String getNumble() {
			return numble;
		}
		public void setNumble(String numble) {
			this.numble = numble;
		}
		public Map<String, Student> getStudents() {
			return students;
		}
		public void setStudents(Map<String, Student> students) {
			this.students = students;
		}
		@Override
		public String toString() {
			return "clazz [numble=" + numble + ", students=" + students + "]";
		}
	}
	//Student
	public class Student {
		private String name;
		
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Student() {
			super();
		}
		public Student(String name) {
			super();
			this.name = name;
		}
		@Override
		public String toString() {
			return "Student [name=" + name + "]";
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Clazz clazz = (Clazz) ctx.getBean("clazz");
			System.out.println(clazz);
		}
	}
	//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="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
		<bean id="student1" class="beans.Student">
			<property name="name" value="student1"/>
		</bean>
		<bean id="student2" class="beans.Student">
			<property name="name" value="student2"/>
		</bean>
		<bean id="clazz" class="beans.Clazz">
			<property name="numble" value="1" />
			<property name="students">
				<map>
					<entry key="AA" value-ref="student1" ></entry>
					<entry key="BB" value-ref="student2" ></entry>
				</map>
			</property>
		</bean>
	</beans>
//Properties属性配置
	//DataSource
	public class DataSource {
		private Properties properties;

		public Properties getProperties() {
			return properties;
		}

		public void setProperties(Properties properties) {
			this.properties = properties;
		}

		@Override
		public String toString() {
			return "DataSource [properties=" + properties + "]";
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			DataSource dataSource = (DataSource) ctx.getBean("Properties");
			System.out.println(dataSource);
		}
	}
	//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="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
		<bean id="Properties" class="beans.DataSource">
			<property name="properties">
				<props>
					<prop key="user">root</prop>
					<prop key="password">root</prop>
					<prop key="jdbcUrl">jdbc:mysql:///test</prop>
					<prop key="driverClass">com.mysql.jdbc.Driver</prop>
				</props>
			</property>
		</bean>
	</beans>
//配置单个集合bean,以供多个bean进行应用,需要导入util命名空间
	//Clazz
	public class Clazz {
		private String numble;
		private List<Student> student;
		public String getNumble() {
			return numble;
		}
		public void setNumble(String numble) {
			this.numble = numble;
		}
		public List<Student> getStudent() {
			return student;
		}
		public void setStudent(List<Student> student) {
			this.student = student;
		}
		@Override
		public String toString() {
			return "Clazz [numble=" + numble + ", student=" + student + "]";
		}
	}
	//Student
	public class Student {
		private String name;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		@Override
		public String toString() {
			return "Student [name=" + name + "]";
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Clazz clazz = (Clazz) ctx.getBean("clazz");
			System.out.println(clazz);
		}
	}
	//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"
		xmlns:util="http://www.springframework.org/schema/util"
		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.1.xsd">
		<bean id="student1" class="beans.Student" >
			<property name="name" value="student1"/>
		</bean>
		<bean id="student2" class="beans.Student" >
			<property name="name" value="student2"/>
		</bean>
		<util:list id="students">
			<ref bean="student1"/>		
			<ref bean="student2"/>		
		</util:list>
		<bean id="clazz" class="beans.Clazz">
			<property name="numble" value="1" />
			<property name="student" ref="students" />
		</bean>
	</beans>
//P命名空间的使用
	//Student
	public class Student {
		private String name;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		@Override
		public String toString() {
			return "Student [name=" + name + "]";
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Student student = (Student) ctx.getBean("student");
			System.out.println(student);
		}
	}
	//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"
		xmlns:util="http://www.springframework.org/schema/util"
		xmlns:p="http://www.springframework.org/schema/p"
		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.1.xsd">
		<bean id="student" p:name="student1" class="beans.Student" />
	</beans>
//自动装配
	//byName:按名字装配
	//byType:按类型装配
	//Clazz
	public class Clazz {
		private String numble;
		private Student student;
		public String getNumble() {
			return numble;
		}
		public void setNumble(String numble) {
			this.numble = numble;
		}
		public Student getStudent() {
			return student;
		}
		public void setStudent(Student student) {
			this.student = student;
		}
		@Override
		public String toString() {
			return "Clazz [numble=" + numble + ", student=" + student + "]";
		}
	}
	//Student
	public class Student {
		private String name;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		@Override
		public String toString() {
			return "Student [name=" + name + "]";
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Clazz clazz = (Clazz) ctx.getBean("clazz");
			System.out.println(clazz);
		}
	}
	//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"
		xmlns:util="http://www.springframework.org/schema/util"
		xmlns:p="http://www.springframework.org/schema/p"
		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.1.xsd">
		<bean id="student" class="beans.Student" p:name="student"/>
		<bean id="clazz" class="beans.Clazz" p:numble="1" autowire="byType" />
		<bean id="clazz1" class="beans.Clazz" p:numble="1" autowire="byName" />
	</beans>
//bean的继承、抽象、依赖
	//Student
	public class Student {
		private String name;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		@Override
		public String toString() {
			return "Student [name=" + name + "]";
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Student student = (Student) ctx.getBean("student1");
			System.out.println(student);
		}
	}
	//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"
		xmlns:util="http://www.springframework.org/schema/util"
		xmlns:p="http://www.springframework.org/schema/p"
		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.1.xsd">
			//抽象beans不能被实例化abstract="true" 
			//依赖必须事先定义depends-on="student",否则报错
		<bean id="student" class="beans.Student" p:name="student" />
		<bean id="student1" p:name="student1" parent="student" />
	</beans>
//bean的作用域
	//singleton:默认值,容器初始化创建bean实例,在整个容器的生命周期内只创建一个bean,单例的
	//prototype:原型的,容器初始化时不创建bean实例,而在每次请求时都创建一个新的Bean实例,并返回
	//Student
	public class Student {
		private String name;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		@Override
		public String toString() {
			return "Student [name=" + name + "]";
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Student student = (Student) ctx.getBean("student");
			Student student1 = (Student) ctx.getBean("student");
			System.out.println(student==student1);
		}
	}
	//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"
		xmlns:util="http://www.springframework.org/schema/util"
		xmlns:p="http://www.springframework.org/schema/p"
		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.1.xsd">
			//使用 scope="prototype",每次初始化,创建新的bean
		<bean id="student" class="beans.Student" p:name="student" scope="prototype"/>
	</beans>
//使用外部属性文件
	//导入c3p0-0.9.2.1.jar、spring-beans-4、mchange-commons-java-0.2.9.jar
	//在src下创建db.properties
	user=root
	password=root
	jdbcUrl=jdbc:mysql:///java
	driverClass=com.mysql.jdbc.Driver
	//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"
		xmlns:context="http://www.springframework.org/schema/context"
		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-4.1.xsd">
		<!-- 导入外部属性文件 -->
		<context:property-placeholder location="classpath:db.properties"/>
		<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
			<property name="user" value="${user}"></property>
			<property name="password" value="${password}"></property>
			<property name="jdbcUrl" value="${jdbcUrl}"></property>
			<property name="driverClass" value="${driverClass}"></property>
		</bean>
	</beans>
	//Testspring
	public class Testspring {
		public static void main(String[] args) throws SQLException {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			DataSource dataSources = (DataSource) ctx.getBean("dataSource");
			System.out.println(dataSources.getConnection());
		}
	}
//spEL
	//表示小数:#{10.0}
	//表示整数:#{10}
	//表示布尔值:#{false}
	//表示字符串:#{'表示'}
	//引用其他对象:<property name="student" value="#{student}"></property>
	//引用其他对象的属性:<property name="student" value="#{student.name}"></property>
	//引用其他对象的方法:<property name="student" value="#{student.toString()}"></property>
	//支持算数运算符:+-*/%^
	//加号还可以用作字符串连接
	//比较运算符:<,>,==,<=,>=,lt,gt,eq,le,ge
	//逻辑运算符:and,or,not,|
	//if-else运算符:三目运算
	//if-else的变体
	//正则表达式matches
	//静态方法静态属性:<property name="initValue" value="#{T(java.lang.Math).PI}"></property>
//Spring管理bean的生命周期
	//init-method=""  destory-method=""
	//配置bean的后置处理器
		//实现BeanPostProcessor,重写2方法,一个init-method之前调用,一个之后调用
//静态工厂方法		
	//Student
	public class Student {
		private String name;
		private String age;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getAge() {
			return age;
		}
		public void setAge(String age) {
			this.age = age;
		}
		public Student(String name, String age) {
			super();
			this.name = name;
			this.age = age;
		}
		@Override
		public String toString() {
			return "Student [name=" + name + ", age=" + age + "]";
		}
		public Student() {
			super();
		}
	}
	//StaticFactory
	public class StaticFactory {
		private static Map<String, Student> student = new HashMap<String, Student>();
		static{
			student.put("student1", new Student("student1","11"));
			student.put("student2", new Student("student2","12"));
		}
		public static Student getStudent(String name){
			return student.get(name);
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args){
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Student student = (Student) ctx.getBean("student1");
			System.out.println(student);
		}
	}
	//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"
		xmlns:context="http://www.springframework.org/schema/context"
		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-4.1.xsd">
		<bean id="student1" class="beans.StaticFactory" factory-method="getStudent">
			<constructor-arg value="student1"></constructor-arg>
		</bean>
	</beans>
//实例工厂方法	
	//Student
	public class Student {
		private String name;
		private String age;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getAge() {
			return age;
		}
		public void setAge(String age) {
			this.age = age;
		}
		public Student(String name, String age) {
			super();
			this.name = name;
			this.age = age;
		}
		@Override
		public String toString() {
			return "Student [name=" + name + ", age=" + age + "]";
		}
		public Student() {
			super();
		}
	}
	//InstanceFactory
	public class InstanceFactory {
		private static Map<String, Student> student =null;
		public InstanceFactory() {
			student = new HashMap<String, Student>();
			student.put("student1", new Student("student1","11"));
			student.put("student2", new Student("student2","12"));
		}
		public  Student getStudent(String name){
			return student.get(name);
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args){
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Student student = (Student) ctx.getBean("student1");
			System.out.println(student);
		}
	}
	//applicationContext.xml
	<?xml version="1.0" encoding="UTF-8"?>
//工厂方法
	//Student
	public class Student {
		private String name;
		private String age;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getAge() {
			return age;
		}
		public void setAge(String age) {
			this.age = age;
		}
		public Student(String name, String age) {
			super();
			this.name = name;
			this.age = age;
		}
		@Override
		public String toString() {
			return "Student [name=" + name + ", age=" + age + "]";
		}
		public Student() {
			super();
		}
	}
	//StudentFactoryBean
	public class StudentFactoryBean implements FactoryBean<Student> {
		private String name;
		public void setName(String name) {
			this.name = name;
		}
		@Override
		public Student getObject() throws Exception {
			return  new Student(name,"11");
		}
		@Override
		public Class<?> getObjectType() {
			return Student.class;
		}
		@Override
		public boolean isSingleton() {
			return true;
		}
	}
	//Testspring
	public class Testspring {
		public static void main(String[] args){
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Student student = (Student) ctx.getBean("student1");
			System.out.println(student);
		}
	}
	//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"
		xmlns:context="http://www.springframework.org/schema/context"
		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-4.1.xsd">
		<bean id="student1" class="beans.StudentFactoryBean">
			<property name="name" value="student1"></property>
		</bean>
	</beans>
//通过注解设置bean
	//在classpath中扫描组件
		//@Component:基本注解,标识一个Spring管理的组件
		//@Respository:标识持久层组件
		//@Service:标识服务层(业务层)组件
		//@Controller:标识表现层组件
	//加入spring-aop-4.1.6.RELEASE.jar
	//Main
	public class Main {
		public static void main(String[] args){
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			TestObject testObject = (TestObject) ctx.getBean("testObject");
			System.out.println(testObject);
			UserController userController= (UserController) ctx.getBean("userController");
			System.out.println(userController);
			UserRepository userRepository= (UserRepository) ctx.getBean("userRepository");
			System.out.println(userRepository);
			UserService userService = (UserService) ctx.getBean("userService");
			System.out.println(userService);
		}
	}
	//TestObject
	@Component
	public class TestObject {
	}
	//Controller
	@Controller
	public class UserController {

	}
	//UserRepository
	public interface UserRepository {
		public void save();
	}
	//UserRepositoryImpls
	@Repository("userRepository")
	public class UserRepositoryImpl implements UserRepository {
		@Override
		public void save() {
		}
	}
	//UserService.java
	@Service
	public class UserService {
	}
	//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"
		xmlns:context="http://www.springframework.org/schema/context"
		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-4.1.xsd">
		<!-- 指定Spring IOC容器扫描的包 -->
		<context:component-scan base-package="main"></context:component-scan>
	</beans>
	//context:exclude-filter(排除那些):<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
	//context:include-filter(包含那些):但是必须在context:component-scan节点中设置use-default-filters="false"
//前置通知
	//使用AspectJ
		//加入aopalliance.jar、aspectjrt.jar、aspectjweaver.jar包
		//Calculator
		public interface Calculator {
			int add(int i,int j);
			int sub(int i,int j);
			int mul(int i,int j);
			int div(int i,int j);
		}
		//CalculatorImpl
		@Component
		public class CalculatorImpl implements Calculator {
			@Override
			public int add(int i, int j) {
				return i+j;
			}
			@Override
			public int sub(int i, int j) {
				return i-j;
			}
			@Override
			public int mul(int i, int j) {
				return i*j;
			}
			@Override
			public int div(int i, int j) {
				return i/j;
			}
		}
		//LoggingAspect
		@Component
		@Aspect
		public class LoggingAspect {
			@Before("execution(public int main.CalculatorImpl.*(int, int))")
			public void beforeMethod(JoinPoint joinPoint){
				String methodName = joinPoint.getSignature().getName();
				List<Object> args = Arrays.asList(joinPoint.getArgs());
				System.out.println("The method "+ methodName +" begin with " + args);
			}
		}
		//Main
		public class Main {
			public static void main(String[] args) {
				ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
				Calculator calculator = ctx.getBean(Calculator.class);
				System.out.println("result:"+calculator.add(2, 3));
				System.out.println("result:"+calculator.div(2, 3));
			}
		}
		//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"
			xmlns:aop="http://www.springframework.org/schema/aop"
			xmlns:context="http://www.springframework.org/schema/context"
			xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
				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-4.1.xsd">
			<context:component-scan base-package="main" annotation-config="true"></context:component-scan>
			<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
		</beans>
		//@Before:前置通知
		//@After:后置通知
		//@AfterRunning:返回通知
		//@AfterThrowing:异常通知
		//@Arcund:环绕通知
//后置、返回、异常、环绕
		@After("execution(public int main.CalculatorImpl.*(int, int))")
		public void afterMethod(JoinPoint joinPoint){
			String methodName = joinPoint.getSignature().getName();
			List<Object> args = Arrays.asList(joinPoint.getArgs());
			System.out.println("The method "+ methodName +" end with ");
		}
		@AfterReturning(value="execution(public int main.CalculatorImpl.*(int, int))",returning="result")
		public void afterReturningMethod(JoinPoint joinPoint,Object result){
			String methodName = joinPoint.getSignature().getName();
			System.out.println("The method "+ methodName +" end with "+ result);
		}
		//异常通知
		@AfterThrowing(value="execution(public int main.CalculatorImpl.*(int, int))",throwing="ex")
		public void afterThrowing(JoinPoint joinPoint,Exception ex){
			String methodName = joinPoint.getSignature().getName();
			System.out.println("The method "+ methodName +" occurs excetion:  "+ ex);
		}
		//环绕通知
		@Around("execution(public int main.CalculatorImpl.*(int, int))")
		public Object aroundMethod(ProceedingJoinPoint pjd){
			Object result = null;
			String methodName = pjd.getSignature().getName();
			try{
				//前置通知
				System.out.println("The method "+ methodName +" begin with " + Arrays.asList(pjd.getArgs()));
				result = pjd.proceed();
				//返回通知
				System.out.println("The method "+ methodName +" end with "+ result);
			}catch(Throwable e){
				//异常通知
				System.out.println("The method "+ methodName +" occurs exception: "+e);
				throw new RuntimeException(e);
			}
			//后置通知
			System.out.println("The method " + methodName + "ends");
			return result;
		}	
//设置切面优先级
	//@Order(1) 数字越小,优先级越高
//重用切点
	//declareJontPointExpression
	@Pointcut("execution(public int main.CalculatorImpl.*(int, int))")
	public void declareJontPointExpression(){
		
	}
	//beforeMethod
	@Before("declareJontPointExpression()")
	public void beforeMethod(JoinPoint joinPoint){
		String methodName = joinPoint.getSignature().getName();
		List<Object> args = Arrays.asList(joinPoint.getArgs());
		System.out.println("The method "+ methodName +" begin with " + args);
	}	
	//(包名.类名.方法名)
//使用配置文件方式配置AOP
	//Calculator
	public interface Calculator {
		int add(int i,int j);
		int sub(int i,int j);
		int mul(int i,int j);
		int div(int i,int j);
	}
	//CalculatorImpl
	@Component
	public class CalculatorImpl implements Calculator {
		@Override
		public int add(int i, int j) {
			return i+j;
		}
		@Override
		public int sub(int i, int j) {
			return i-j;
		}
		@Override
		public int mul(int i, int j) {
			return i*j;
		}
		@Override
		public int div(int i, int j) {
			return i/j;
		}
	}
	//Main
	public class Main {
		public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			Calculator calculator = ctx.getBean(Calculator.class);
			System.out.println("result:"+calculator.div(2, 1));
		}
	}
	//LoggingAspect
	@Component
	public class LoggingAspect {
		public void declareJontPointExpression(){
			
		}
		public void beforeMethod(JoinPoint joinPoint){
			String methodName = joinPoint.getSignature().getName();
			List<Object> args = Arrays.asList(joinPoint.getArgs());
			System.out.println("The method "+ methodName +" begin with " + args);
		}
		public void afterMethod(JoinPoint joinPoint){
			String methodName = joinPoint.getSignature().getName();
			List<Object> args = Arrays.asList(joinPoint.getArgs());
			System.out.println("The method "+ methodName +" end with ");
		}
		public void afterReturningMethod(JoinPoint joinPoint,Object result){
			String methodName = joinPoint.getSignature().getName();
			System.out.println("The method "+ methodName +" end with "+ result);
		}
		//异常通知
		public void afterThrowing(JoinPoint joinPoint,Exception ex){
			String methodName = joinPoint.getSignature().getName();
			System.out.println("The method "+ methodName +" occurs excetion:  "+ ex);
		}
		//环绕通知
		public Object aroundMethod(ProceedingJoinPoint pjd){
			Object result = null;
			String methodName = pjd.getSignature().getName();
			try{
				//前置通知
				System.out.println("The method "+ methodName +" begin with " + Arrays.asList(pjd.getArgs()));
				result = pjd.proceed();
				//返回通知
				System.out.println("The method "+ methodName +" end with "+ result);
			}catch(Throwable e){
				//异常通知
				System.out.println("The method "+ methodName +" occurs exception: "+e);
				throw new RuntimeException(e);
			}
			//后置通知
			System.out.println("The method " + methodName + "ends");
			return result;
		}
	}
	//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"
		xmlns:aop="http://www.springframework.org/schema/aop"
		xmlns:context="http://www.springframework.org/schema/context"
		xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
			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-4.1.xsd">
		<!-- 配置Bean -->
		<bean id="Calculator" class="main.CalculatorImpl"></bean>
		<!-- 配置切面bean -->
		<bean id="LoggingAspect" class="main.LoggingAspect"></bean>
		<!-- 配置AOP -->
		<aop:config>
			<!-- 配置切点表达式 -->
			<aop:pointcut expression="execution(* main.Calculator.*(int,int) )" id="pointcut"/>
			<!-- 配置切面通知 -->
			<aop:aspect ref="LoggingAspect" order="1">
				<aop:before method="beforeMethod" pointcut-ref="pointcut"/>
				<aop:after method="afterMethod" pointcut-ref="pointcut"/>
				<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="ex"/>
				<aop:after-returning method="afterReturningMethod" pointcut-ref="pointcut" returning="result"/>
				<!-- <aop:around method="aroundMethod" pointcut-ref="pointcut"/> -->
			</aop:aspect>
		</aop:config>
	</beans>
//JdbcTemplate
	//导入spring-jdbc-4.1.6.RELEASE.jar、spring-tx-4.1.6.RELEASE.jar
	//User
	public class User {
		private int id;
		private String username;
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getUsername() {
			return username;
		}
		public void setUsername(String username) {
			this.username = username;
		}
		@Override
		public String toString() {
			return "User [id=" + id + ", username=" + username + "]";
		}
	}
	//TestJdbc
	public class TestJdbc {
		private ApplicationContext ctx = null;
		private JdbcTemplate jdbcTemplate;
		{
			ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
		}
		@Test
		public void testQueryForObject2(){
			String sql = "select count(id) from users";
			long count = jdbcTemplate.queryForObject(sql, Long.class);
			System.out.println(count);
		}
		@Test
		public void testQueryForList(){
			String sql = "select id,username from users where id >?";
			List<User> users = jdbcTemplate.query(sql,new BeanPropertyRowMapper(User.class),0);
			System.out.println(users);
		}
		@Test
		public void testQueryForObject(){
			String sql = "select id, username from users where id =?";
			User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper(User.class),1);
			System.out.println(user);
		}
		@Test
		public void testBatchInsert(){
			String sql = "insert into users(username)values(?)";
			List<Object[]> batchArgs = new ArrayList<Object[]>();
			batchArgs.add(new Object[]{"studnet1"});
			batchArgs.add(new Object[]{"studnet2"});
			batchArgs.add(new Object[]{"studnet3"});
			batchArgs.add(new Object[]{"studnet4"});
			batchArgs.add(new Object[]{"studnet5"});
			jdbcTemplate.batchUpdate(sql,batchArgs);
		}
		@Test
		public void testUpdate(){
			String sql = "update users set username =? where id = ? ";
			jdbcTemplate.update(sql,"student",1);
		}
		@Test
		public void testDataSource() throws SQLException{
			DataSource dataSources = ctx.getBean(DataSource.class);
			System.out.println(dataSources.getConnection());
		}
	}
	//UserDAO
	public class UserDAO {
		@Autowired
		private JdbcTemplate jdbcTemplate;
		
		public User get(Integer id){
			String sql = "select id, username from users where id =?";
			User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper(User.class),1);
			return user;
		}
	}
	//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"
		xmlns:context="http://www.springframework.org/schema/context"
		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-4.1.xsd">
		<!-- 导入资源文件 -->
		<context:property-placeholder location="classpath:db.properties"/>
		<!-- 配置C3P0数据源 -->
		<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
			<property name="user" value="${jdbc.user}"></property>
			<property name="password" value="${jdbc.password}"></property>
			<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
			<property name="driverClass" value="${jdbc.driverClass}"></property>
			<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
			<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
		</bean>
		
		<!-- 配置Spring的JdbcTemplate -->
		<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
			<property name="dataSource" ref="dataSource"></property>
		</bean>
	</beans>
	//db.properties
	jdbc.user=root
	jdbc.password=root
	jdbc.driverClass=com.mysql.jdbc.Driver
	jdbc.jdbcUrl=jdbc:mysql:///java
	jdbc.initialPoolSize=10
	jdbc.maxPoolSize=5
//NamedParameterJdbcTemlate
//事务
	//使用注解
		//BookShopDao
		public interface BookShopDao {
			public int findBookPriceByIsbn(String isbn);
			public void updateBookStock(String isbn);
			public void updateUserAccount(String username,int price);
		}
		//BookShopDaoImpl
		@Repository("bookShopDao")
			public class BookShopDaoImpl implements BookShopDao {
			@Autowired
			private JdbcTemplate jdbcTemplate;
			@Override
			public int findBookPriceByIsbn(String isbn) {
				String sql = "select price from book where isbn = ?";
				return jdbcTemplate.queryForObject(sql, Integer.class,isbn);
			}

			@Override
			public void updateBookStock(String isbn) {
				String sql2 = "select stock from book_stock where isbn = ? ";
				int stock = jdbcTemplate.queryForObject(sql2,Integer.class,isbn);
				if(stock == 0){
					throw new BookStockException("库存不足");
				}
				String sql = "update book_stock set stock = stock-1 where isbn = ?";
				jdbcTemplate.update(sql,isbn);
			}

			@Override
			public void updateUserAccount(String username, int price) {
				String sql2 = "select balance from account where username = ?";
				int balance = jdbcTemplate.queryForObject(sql2, Integer.class,username);
				if(balance < price){
					throw new UserAccountException("余额不足");
				}
				String sql = "update account set balance = balance - ? where username=?";
				jdbcTemplate.update(sql,price,username);
			}

		}
		//BookShopService
		public interface BookShopService {
			public void purchase(String username,String isbn);
		}
		//BookShopServiceImpl
		@Service("bookShopService")
		public class BookShopServiceImpl implements BookShopService {
			@Autowired
			private BookShopDao bookShopDao;
			
			//添加事务注解
			@Transactional(propagation=Propagation.REQUIRED,//事务的传播行为
							isolation=Isolation.READ_COMMITTED,//事务的隔离级别
							readOnly=false,//是否只读
							timeout=3)//限制时间
			@Override
			public void purchase(String username, String isbn) {
				int price = bookShopDao.findBookPriceByIsbn(isbn);
				bookShopDao.updateBookStock(isbn);
				bookShopDao.updateUserAccount(username, price);
			}

		}
		//BookStockException
		public class BookStockException extends RuntimeException {

			public BookStockException() {
				super();
				// TODO Auto-generated constructor stub
			}

			public BookStockException(String message, Throwable cause) {
				super(message, cause);
				// TODO Auto-generated constructor stub
			}

			public BookStockException(String message) {
				super(message);
				// TODO Auto-generated constructor stub
			}

			public BookStockException(Throwable cause) {
				super(cause);
				// TODO Auto-generated constructor stub
			}
		}
		//Cashiser
		public interface Cashiser {
			public void checkout(String username,List<String> isbns);
		}
		//CashiserImpl
		@Service("cashiser")
		public class CashiserImpl implements Cashiser {
			@Autowired
			private BookShopService bookShopService;
			@Transactional
			@Override
			public void checkout(String username, List<String> isbns) {
				for(String isbn:isbns){
					bookShopService.purchase(username, isbn);
				}
			}

		}
		//SpringTransactionTest
		public class SpringTransactionTest {
			private ApplicationContext ctx = null;
			private BookShopDao bookShopDao = null;
			private BookShopService bookShopService = null;
			private Cashiser cashiser = null;
			{
				ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
				bookShopDao = ctx.getBean(BookShopDao.class);
				bookShopService = ctx.getBean(BookShopService.class);
				cashiser = ctx.getBean(Cashiser.class);
			}	
			@Test
			public void testTransactionPropagation(){
				cashiser.checkout("student", Arrays.asList("1","2"));
			}
			@Test
			public void testBookShopService(){
				bookShopService.purchase("student", "2");
			}
			@Test
			public void testBookShopDaoUpdateUserAccount(){
				bookShopDao.updateUserAccount("student", 110);
			}
			@Test
			public void testBookShopDaoUpdateBookStock(){
				bookShopDao.updateBookStock("1");
			}
			@Test
			public void testBookShopDaoFindPriceByIsbn(){
				System.out.println(bookShopDao.findBookPriceByIsbn("1"));
			}
		}
		//UserAccountException
		public class UserAccountException extends RuntimeException {

			public UserAccountException() {
				super();
				// TODO Auto-generated constructor stub
			}

			public UserAccountException(String message, Throwable cause) {
				super(message, cause);
				// TODO Auto-generated constructor stub
			}

			public UserAccountException(String message) {
				super(message);
				// TODO Auto-generated constructor stub
			}

			public UserAccountException(Throwable cause) {
				super(cause);
				// TODO Auto-generated constructor stub
			}
		}
		//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"
			xmlns:context="http://www.springframework.org/schema/context"
			xmlns:tx="http://www.springframework.org/schema/tx"
			xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
			<!-- 导入资源文件 -->
			<context:property-placeholder location="classpath:db.properties"/>
			<!-- 自动扫描 -->
			<context:component-scan base-package="main"></context:component-scan>
			<!-- 配置C3P0数据源 -->
			<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
				<property name="user" value="${jdbc.user}"></property>
				<property name="password" value="${jdbc.password}"></property>
				<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
				<property name="driverClass" value="${jdbc.driverClass}"></property>
				<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
				<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
			</bean>
			
			<!-- 配置Spring的JdbcTemplate -->
			<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
				<property name="dataSource" ref="dataSource"></property>
			</bean>
			
			<!-- 配置事务管理器 -->
			<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
				<property name="dataSource" ref="dataSource"></property>
			</bean>
			<!-- 启用事务注解 -->
			<tx:annotation-driven transaction-manager="transactionManager" />
		</beans>
		//db.properties
		jdbc.user=root
		jdbc.password=root
		jdbc.driverClass=com.mysql.jdbc.Driver
		jdbc.jdbcUrl=jdbc:mysql:///java
		jdbc.initialPoolSize=10
		jdbc.maxPoolSize=5
		//sql
		DROP TABLE IF EXISTS `account`;
		CREATE TABLE `account` (
		  `username` varchar(50) NOT NULL,
		  `balance` int(11) DEFAULT NULL,
		  PRIMARY KEY (`username`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8;

		-- ----------------------------
		-- Records of account
		-- ----------------------------
		INSERT INTO `account` VALUES ('student', '0');

		-- ----------------------------
		-- Table structure for `book`
		-- ----------------------------
		DROP TABLE IF EXISTS `book`;
		CREATE TABLE `book` (
		  `isbn` varchar(50) NOT NULL,
		  `book_name` varchar(100) DEFAULT NULL,
		  `price` int(11) DEFAULT NULL,
		  PRIMARY KEY (`isbn`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8;

		-- ----------------------------
		-- Records of book
		-- ----------------------------
		INSERT INTO `book` VALUES ('1', 'Java', '50');
		INSERT INTO `book` VALUES ('2', 'Orancle', '20');
		INSERT INTO `book` VALUES ('3', 'Mysql', '40');

		-- ----------------------------
		-- Table structure for `book_stock`
		-- ----------------------------
		DROP TABLE IF EXISTS `book_stock`;
		CREATE TABLE `book_stock` (
		  `isbn` varchar(50) NOT NULL,
		  `stock` int(11) DEFAULT NULL,
		  PRIMARY KEY (`isbn`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8;

		-- ----------------------------
		-- Records of book_stock
		-- ----------------------------
		INSERT INTO `book_stock` VALUES ('1', '1');
		INSERT INTO `book_stock` VALUES ('2', '1');
		INSERT INTO `book_stock` VALUES ('3', '10');
		
	//使用XML
		//目录结构
			//main
				BookShopDao.java
				BookShopDaoImpl.java
				BookStockException.java
				SpringTransactionTest.java
				UserAccountException.java
			//service	
				BookShopService.java
				Cashiser.java
			//service.impl	
				BookShopServiceImpl.java
				CashiserImpl.java
			applicationContext.xml	
			db.properties	
		//BookShopDao		
		public interface BookShopDao {
			public int findBookPriceByIsbn(String isbn);
			public void updateBookStock(String isbn);
			public void updateUserAccount(String username,int price);
		}
		//BookShopDaoImpl		
		public class BookShopDaoImpl implements BookShopDao {
			private JdbcTemplate jdbcTemplate;
			public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
				this.jdbcTemplate = jdbcTemplate;
			}
			@Override
			public int findBookPriceByIsbn(String isbn) {
				String sql = "select price from book where isbn = ?";
				return jdbcTemplate.queryForObject(sql, Integer.class,isbn);
			}

			@Override
			public void updateBookStock(String isbn) {
				String sql2 = "select stock from book_stock where isbn = ? ";
				int stock = jdbcTemplate.queryForObject(sql2,Integer.class,isbn);
				if(stock == 0){
					throw new BookStockException("库存不足");
				}
				String sql = "update book_stock set stock = stock-1 where isbn = ?";
				jdbcTemplate.update(sql,isbn);
			}

			@Override
			public void updateUserAccount(String username, int price) {
				String sql2 = "select balance from account where username = ?";
				int balance = jdbcTemplate.queryForObject(sql2, Integer.class,username);
				if(balance < price){
					throw new UserAccountException("余额不足");
				}
				String sql = "update account set balance = balance - ? where username=?";
				jdbcTemplate.update(sql,price,username);
			}
		}
		//BookStockException		
		public class BookStockException extends RuntimeException {
			public BookStockException() {
				super();
				// TODO Auto-generated constructor stub
			}
			public BookStockException(String message, Throwable cause) {
				super(message, cause);
				// TODO Auto-generated constructor stub
			}
			public BookStockException(String message) {
				super(message);
				// TODO Auto-generated constructor stub
			}
			public BookStockException(Throwable cause) {
				super(cause);
				// TODO Auto-generated constructor stub
			}
		}
		//SpringTransactionTest		
		public class SpringTransactionTest {
			private ApplicationContext ctx = null;
			private BookShopDao bookShopDao = null;
			private BookShopService bookShopService = null;
			private Cashiser cashiser = null;
			{
				ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
				bookShopDao = ctx.getBean(BookShopDao.class);
				bookShopService = ctx.getBean(BookShopService.class);
				cashiser = ctx.getBean(Cashiser.class);
			}	
			@Test
			public void testTransactionPropagation(){
				cashiser.checkout("student", Arrays.asList("1","2"));
			}
			@Test
			public void testBookShopService(){
				bookShopService.purchase("student", "2");
			}
		}
		//UserAccountException		
		public class UserAccountException extends RuntimeException {
			public UserAccountException() {
				super();
				// TODO Auto-generated constructor stub
			}
			public UserAccountException(String message, Throwable cause) {
				super(message, cause);
				// TODO Auto-generated constructor stub
			}
			public UserAccountException(String message) {
				super(message);
				// TODO Auto-generated constructor stub
			}
			public UserAccountException(Throwable cause) {
				super(cause);
				// TODO Auto-generated constructor stub
			}
		}
		//BookShopService		
		public interface BookShopService {
			public void purchase(String username,String isbn);
		}
		//Cashiser		
		public interface Cashiser {
			public void checkout(String username,List<String> isbns);
		}
		//BookShopServiceImpl		
		public class BookShopServiceImpl implements BookShopService {
			private BookShopDao bookShopDao;
			public void setBookShopDao(BookShopDao bookShopDao) {
				this.bookShopDao = bookShopDao;
			}
			@Override
			public void purchase(String username, String isbn) {
				int price = bookShopDao.findBookPriceByIsbn(isbn);
				bookShopDao.updateBookStock(isbn);
				bookShopDao.updateUserAccount(username, price);
			}
		}
		//CashiserImpl		
		public class CashiserImpl implements Cashiser {
			private BookShopService bookShopService;
			public void setBookShopService(BookShopService bookShopService) {
				this.bookShopService = bookShopService;
			}
			@Override
			public void checkout(String username, List<String> isbns) {
				for(String isbn:isbns){
					bookShopService.purchase(username, isbn);
				}
			}
		}
		//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"
			xmlns:context="http://www.springframework.org/schema/context"
			xmlns:tx="http://www.springframework.org/schema/tx"
			xmlns:aop="http://www.springframework.org/schema/aop"
			xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
				http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
			<!-- 导入资源文件 -->
			<context:property-placeholder location="classpath:db.properties"/>
			<!-- 配置C3P0数据源 -->
			<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
				<property name="user" value="${jdbc.user}"></property>
				<property name="password" value="${jdbc.password}"></property>
				<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
				<property name="driverClass" value="${jdbc.driverClass}"></property>
				<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
				<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
			</bean>
			
			<!-- 配置Spring的JdbcTemplate -->
			<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
				<property name="dataSource" ref="dataSource"></property>
			</bean>
			<!-- 配置bean -->
			<bean id="bookShopDao" class="main.BookShopDaoImpl">
				<property name="jdbcTemplate" ref="jdbcTemplate"></property>
			</bean>
			
			<bean id="bookShopService" class="service.impl.BookShopServiceImpl">
				<property name="bookShopDao" ref="bookShopDao"></property>
			</bean>
			
			<bean id="cashier" class="service.impl.CashiserImpl">
				<property name="bookShopService" ref="bookShopService"></property>
			</bean>
			<!-- 配置事务管理器 -->
			<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
				<property name="dataSource" ref="dataSource"></property>
			</bean>
			<!-- 配置事务属性 -->
			<tx:advice id="txAdvice" transaction-manager="transactionManager">
				<tx:attributes>
					<!-- 根据方法名指定事务属性 -->
					<tx:method name="prchase" propagation="REQUIRES_NEW"/>
					<tx:method name="get*" read-only="true"/>
					<tx:method name="find*" read-only="true"/>
					<tx:method name="*"/>
				</tx:attributes>
			</tx:advice>
			<!-- 配置事务切入点 -->
			<aop:config>
				<aop:pointcut expression="execution(* service.BookShopService.*(..))" id="txPointCut"/>
				<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
			</aop:config>
		</beans>
		//db.properties		
		jdbc.user=root
		jdbc.password=root
		jdbc.driverClass=com.mysql.jdbc.Driver
		jdbc.jdbcUrl=jdbc:mysql:///java
		jdbc.initialPoolSize=10
		jdbc.maxPoolSize=5
//整合hibernate
	//目录结构			
	src
		dao
			impl
				BookShopDaoImpl.java
			BookShopDao.java
		entities
			Account.java
			Book.java
			Account.hbm.xml
			Book.hbm.xml
		exception
			BookStockException.java
			UserAccountException.java
		service
			impl
				BookShopServiceImpl.java
				CashierImpl.java
			BookShopService.java
			Cashier.java
		test
			TestSH.java
		applicationContext.xml
		db.properties
		hibernate.cfg.xml
	//BookShopDaoImpl
	@Repository
	public class BookShopDaoImpl implements BookShopDao {
		@Autowired
		private SessionFactory sessionFactory;
		//获得和当前线程绑定的Session
		public Session getSession() {
			return sessionFactory.getCurrentSession();
		}
		@Override
		public int findBookPriceByIsbn(String isbn) {
			String hql = "select b.price from Book b where b.isbn = ?";
			Query query = getSession().createQuery(hql).setString(0, isbn);
			return (Integer) query.uniqueResult();
		}

		@Override
		public void updateBookStock(String isbn) {
			//验证库存是否充足
			String hql2 = "select b.stock from Book b where b.isbn=?";
			int stock = Integer.parseInt(getSession().createQuery(hql2).setString(0, isbn).uniqueResult().toString());
			if(stock == 0){
				throw new BookStockException("库存不足");
			}
			String hql = "update Book b set b.stock = b.stock - 1 where b.isbn = ?";
			getSession().createQuery(hql).setString(0, isbn).executeUpdate();
		}

		@Override
		public void updateUserAccount(String username, int price) {
			//验证余额不足
			String hql2 = "select a.balance from Account a where a.username = ?";
			int balance = Integer.parseInt(getSession().createQuery(hql2).setString(0, username).uniqueResult().toString());
			if(balance < price){
				throw new UserAccountException("余额不足");
			}
			String hql = "update Account a set a.balance = a.balance - ? where a.username=?";
			getSession().createQuery(hql).setInteger(0, price).setString(1, username).executeUpdate();
		}

	}
	//BookShopDao
	public interface BookShopDao {
		public int findBookPriceByIsbn(String isbn);
		public void updateBookStock(String isbn);
		public void updateUserAccount(String username,int price);
	}	
	//Account
	public class Account {
		private Integer id;
		private String username;
		private Integer balance;
		public Integer getId() {
			return id;
		}
		public void setId(Integer id) {
			this.id = id;
		}
		public String getUsername() {
			return username;
		}
		public void setUsername(String username) {
			this.username = username;
		}
		public Integer getBalance() {
			return balance;
		}
		public void setBalance(Integer balance) {
			this.balance = balance;
		}
	}	
	//Book
	public class Book {
		private Integer id;
		private String book;
		private String isbn;
		private Integer price;
		private Integer stock;
		public Integer getId() {
			return id;
		}
		public void setId(Integer id) {
			this.id = id;
		}
		public String getBook() {
			return book;
		}
		public void setBook(String book) {
			this.book = book;
		}
		public String getIsbn() {
			return isbn;
		}
		public void setIsbn(String isbn) {
			this.isbn = isbn;
		}
		public Integer getPrice() {
			return price;
		}
		public void setPrice(Integer price) {
			this.price = price;
		}
		public Integer getStock() {
			return stock;
		}
		public void setStock(Integer stock) {
			this.stock = stock;
		}
	}
	//Account.hbm.xml
	<?xml version="1.0"?>
	<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
	<!-- Generated 2016-6-11 14:42:55 by Hibernate Tools 3.4.0.CR1 -->
	<hibernate-mapping>
		<class name="entities.Account" table="ACCOUNT">
			<id name="id" type="java.lang.Integer">
				<column name="ID" />
				<generator class="native" />
			</id>
			<property name="username" type="java.lang.String">
				<column name="USERNAME" />
			</property>
			<property name="balance" type="java.lang.Integer">
				<column name="BALANCE" />
			</property>
		</class>
	</hibernate-mapping>
	//Book.hbm.xml
	<?xml version="1.0"?>
	<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
	<!-- Generated 2016-6-11 14:42:55 by Hibernate Tools 3.4.0.CR1 -->
	<hibernate-mapping>
		<class name="entities.Book" table="BOOK">
			<id name="id" type="java.lang.Integer">
				<column name="ID" />
				<generator class="native" />
			</id>
			<property name="book" type="java.lang.String">
				<column name="BOOK" />
			</property>
			<property name="isbn" type="java.lang.String">
				<column name="ISBN" />
			</property>
			<property name="price" type="java.lang.Integer">
				<column name="PRICE" />
			</property>
			<property name="stock" type="java.lang.Integer">
				<column name="STOCK" />
			</property>
		</class>
	</hibernate-mapping>
	//BookStockException
	public class BookStockException extends RuntimeException{

		public BookStockException() {
			super();
			// TODO Auto-generated constructor stub
		}

		public BookStockException(String message, Throwable cause) {
			super(message, cause);
			// TODO Auto-generated constructor stub
		}

		public BookStockException(String message) {
			super(message);
			// TODO Auto-generated constructor stub
		}

		public BookStockException(Throwable cause) {
			super(cause);
			// TODO Auto-generated constructor stub
		}
	}
	//UserAccountException
	public class UserAccountException extends RuntimeException {
		public UserAccountException() {
			super();
			// TODO Auto-generated constructor stub
		}

		public UserAccountException(String message, Throwable cause) {
			super(message, cause);
			// TODO Auto-generated constructor stub
		}

		public UserAccountException(String message) {
			super(message);
			// TODO Auto-generated constructor stub
		}

		public UserAccountException(Throwable cause) {
			super(cause);
			// TODO Auto-generated constructor stub
		}
	}
	//BookShopServiceImpl
	@Service
	public class BookShopServiceImpl implements BookShopService {
		@Autowired
		private BookShopDao bookShopDao;
		@Override
		public void purchase(String username, String isbn) {
			int price = bookShopDao.findBookPriceByIsbn(isbn);
			bookShopDao.updateBookStock(isbn);
			bookShopDao.updateUserAccount(username, price);
		}
	}
	//CashierImpl
	@Service
	public class CashierImpl implements Cashier {
		@Autowired
		private BookShopService bookShopService;
		@Override
		public void checkout(String username, List<String> isbns) {
			for(String isbn:isbns){
				bookShopService.purchase(username, isbn);
			}
		}
	}
	//BookShopService
	public interface BookShopService {
		public void purchase(String username,String isbn);
	}
	//Cashier
	public interface Cashier {
		public void checkout(String username,List<String> isbns);
	}
	//TestSH
	public class TestSH {
		private ApplicationContext ctx = null;
		private BookShopService bookShopService;
		private Cashier cashier;
		{
			ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
			bookShopService = ctx.getBean(BookShopService.class);
			cashier = ctx.getBean(Cashier.class);
		}
		@Test
		public void testCashier(){
			cashier.checkout("student", Arrays.asList("1","2"));
		}
		@Test
		public void testBookShopService(){
			bookShopService.purchase("student", "1");
		}
		@Test
		public void testDataSource() throws SQLException{
			DataSource dataSource = ctx.getBean(DataSource.class);
			System.out.println(dataSource.getConnection());
			
		}
	}
	//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"
		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/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
		<!-- 自动扫描 -->
		<context:component-scan base-package="*"></context:component-scan>
		<!-- 导入资源文件 -->
		<context:property-placeholder location="classpath:db.properties"/>
		
		<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
			<property name="user" value="${jdbc.user}"></property>
			<property name="password" value="${jdbc.password}"></property>
			<property name="driverClass" value="${jdbc.driverClass}"></property>
			<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
			<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
			<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
		</bean>
		
		<!-- 配置Hibernate 的SessionFactory -->
		<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
			<property name="dataSource" ref="dataSource"></property>
			<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
			<property name="mappingLocations" value="classpath:entities/*.hbm.xml"></property>
		</bean>
		<!-- 配置Spring声明式事务 -->
		<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
			<property name="sessionFactory" ref="sessionFactory"></property>
		</bean>
		<!-- 配置事务属性 -->
		<tx:advice id="txAdvice" transaction-manager="transactionManager">
			<tx:attributes>
				<tx:method name="get*" read-only="true"/>
				<tx:method name="purchase" propagation="REQUIRES_NEW"/>
				<tx:method name="*"/>
			</tx:attributes>
		</tx:advice>
		<!-- 配置事务切点 -->
		<aop:config>
			<aop:pointcut expression="execution(* service.*.*(..))" id="txPointcut"/>
			<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
		</aop:config>
	</beans>
	//db.properties
	jdbc.user=root
	jdbc.password=root
	jdbc.driverClass=com.mysql.jdbc.Driver
	jdbc.jdbcUrl=jdbc:mysql:///java

	jdbc.initialPoolSize=5
	jdbc.maxPoolSize=10
	//hibernate.cfg.xml
	<?xml version="1.0" encoding="UTF-8"?>
	<!DOCTYPE hibernate-configuration PUBLIC
			"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
			"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
	<hibernate-configuration>
		<session-factory>
			<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
			<property name="hibernate.show_sql">true</property>
			<property name="hibernate.hbm2ddl.auto">update</property>
		</session-factory>
	</hibernate-configuration>
//Spring整合Struts	
	//目录结构
	src
		action
			PersonAction.java
		beans
			Person.java
		services
			PersonService.java
		applicationContext.xml
		struts.xml
		WebContent
			META-INF
			WEB-INF
				lib
					web.xml
			index.jsp
			success.jsp
			test.jsp
	//PersonAction
	public class PersonAction {
		private PersonService personService;
		public void setPersonService(PersonService personService) {
			this.personService = personService;
		}
		public String execute(){
			System.out.println("execute....");
			personService.save();
			return "success";
		}
	}
	//Person
	public class Person {
		private String username;
		public void setUsername(String username) {
			this.username = username;
		}
		public void hello(){
			System.out.println("My name is " + username);
		}
	}
	//PersonService
	public class PersonService {
		public void save(){
			System.out.println("PersonService's save....");
		}
	}
	//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="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

		<bean id="person" 
			class="com.atguigu.spring.struts2.beans.Person">
			<property name="username" value="spring"></property>	
		</bean>
		
		<bean id="personService"
			class="com.atguigu.spring.struts2.services.PersonService"></bean>
		
		<!-- 注意: 在 IOC 容器中配置 Struts2 的 Action 时, 需要配置 scope 属性, 其值必须为 prototype -->
		<bean id="personAction" 
			class="com.atguigu.spring.struts2.actions.PersonAction"
			scope="prototype">
			<property name="personService" ref="personService"></property>	
		</bean>
	</beans>
	//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>
		<constant name="struts.enable.DynamicMethodInvocation" value="false" />
		<constant name="struts.devMode" value="true" />
		<package name="default" namespace="/" extends="struts-default">
			<!--  
				Spring 整合 Struts2 时, 在 Struts2 中配置的 Spring 的 Action 的 class 需要指向 IOC 容器中该 bean 的 id
			-->
			<action name="person-save" class="personAction">
				<result>/success.jsp</result>
			</action>
		</package>
	</struts>
	//web.xml
	<?xml version="1.0" encoding="UTF-8"?>
	<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
		<!-- 配置 Spring 配置文件的名称和位置 -->
		<context-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</context-param>
		<!-- 启动 IOC 容器的 ServletContextListener -->
		<listener>
			<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
		</listener>
		<!-- 配置 Struts2 的 Filter -->
		<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>
	//index.jsp
	<body>
		<a href="person-save">Person Save</a>
	</body>
	//success.jsp
	<body>
		<h4>Success Page</h4>
	</body>
	//test.jsp
	<body>
		<% 
		//1. 从 appication 域对象中得到 IOC 容器的实例
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application);
		//2. 从 IOC 容器中得到 bean
		Person person = ctx.getBean(Person.class);
		//3. 使用 bean
		person.hello();
		%>
	</body>
//struts整合spring
	asm-3.3
	asm-commons-3.3
	asm-tree-3.3
	com.springsource.net.sf.cglib-2.2.0
	com.springsource.org.aopalliance-1.0.0
	com.springsource.org.aspectj.weaver-1.6.8.RELEASE
	commons-fileupload-1.3
	commons-io-2.0.1
	commons-lang3-3.1
	commons-logging-1.1.3
	freemarker-2.3.19
	javassist-3.11.0.GA
	log4j-1.2.17
	ognl-3.0.6
	spring-aop-4.0.0.RELEASE
	spring-aspects-4.0.0.RELEASE
	spring-beans-4.0.0.RELEASE
	spring-context-4.0.0.RELEASE
	spring-core-4.0.0.RELEASE
	spring-expression-4.0.0.RELEASE
	spring-jdbc-4.0.0.RELEASE
	spring-orm-4.0.0.RELEASE
	spring-tx-4.0.0.RELEASE
	spring-web-4.0.0.RELEASE
	spring-webmvc-4.0.0.RELEASE
	struts2-core-2.3.15.3
	struts2-spring-plugin-2.3.15.3
	xwork-core-2.3.15.3
//Hibernate整合Spring
	antlr-2.7.7
	c3p0-0.9.1.2
	com.springsource.net.sf.cglib-2.2.0
	com.springsource.org.aopalliance-1.0.0
	com.springsource.org.aspectj.weaver-1.6.8.RELEASE
	commons-logging-1.1.3
	dom4j-1.6.1
	hibernate-commons-annotations-4.0.2.Final
	hibernate-core-4.2.4.Final
	hibernate-jpa-2.0-api-1.0.1.Final
	javassist-3.15.0-GA
	jboss-logging-3.1.0.GA
	jboss-transaction-api_1.1_spec-1.0.1.Final
	mysql-connector-java-5.1.7-bin
	spring-aop-4.0.0.RELEASE
	spring-aspects-4.0.0.RELEASE
	spring-beans-4.0.0.RELEASE
	spring-context-4.0.0.RELEASE
	spring-core-4.0.0.RELEASE
	spring-expression-4.0.0.RELEASE
	spring-jdbc-4.0.0.RELEASE
	spring-orm-4.0.0.RELEASE
	spring-tx-4.0.0.RELEASE
	spring-web-4.0.0.RELEASE
	spring-webmvc-4.0.0.RELEASE

 

转载于:https://my.oschina.net/MoreYoungGavin/blog/689678

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值