开发环境:jdk1.6 Eclipse4.11.0 apache-maven-3.2.5
一、IOC容器
1.BeanFactory容器:
/** * @Title: HelloWorld.java * @Package cn.com.kamfu * @Description: TODO(用一句话描述该文件做什么) * @author: liandy * @date: 2019年7月10日 下午11:58:59 * @version V1.0 */ package cn.com.kamfu; /** * @ClassName: HelloWorld * @Description:TODO(这里用一句话描述这个类的作用) * @author: liandy * @date: 2019年7月10日 下午11:58:59 * */ public class HelloWorld { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
<?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-3.0.xsd"> <bean id="helloWorld" class="cn.com.kamfu.HelloWorld"> <property name="message" value="Hello World!"/> </bean> </beans>
package cn.com.kamfu; import java.io.File; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; /** * Hello world! * */ public class App { public static void main( String[] args ) { // create and configure beans File file=new File("D:\\workspace\\Spring\\src\\main\\java\\beans.xml"); Resource resource=new FileSystemResource(file); BeanFactory beanFactory=new XmlBeanFactory(resource); HelloWorld helloWorld=beanFactory.getBean("helloWorld",HelloWorld.class); System.out.println(helloWorld.getMessage()); } }
2.ApplicationContext容器:
/** * @Title: HelloWorld.java * @Package cn.com.kamfu * @Description: TODO(用一句话描述该文件做什么) * @author: liandy * @date: 2019年7月10日 下午11:58:59 * @version V1.0 */ package cn.com.kamfu; /** * @ClassName: HelloWorld * @Description:TODO(这里用一句话描述这个类的作用) * @author: liandy * @date: 2019年7月10日 下午11:58:59 * */ public class HelloWorld { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
<?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-3.0.xsd"> <bean id="helloWorld" class="cn.com.kamfu.HelloWorld"> <property name="message" value="Hello World!"/> </bean> </beans>
package cn.com.kamfu; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { // create and configure beans ApplicationContext context=new ClassPathXmlApplicationContext("*.xml"); HelloWorld helloWorld=context.getBean("helloWorld",HelloWorld.class); System.out.println(helloWorld.getMessage()); } }
二、Bean
1.定义:用容器提供的配置元数据创建的对象。
2.bean的属性:
3.把配置元数据提供给 Spring容器:
/** * @Title: HelloWorld.java * @Package cn.com.kamfu * @Description: TODO(用一句话描述该文件做什么) * @author: liandy * @date: 2019年7月10日 下午11:58:59 * @version V1.0 */ package cn.com.kamfu; /** * @ClassName: HelloWorld * @Description:TODO(这里用一句话描述这个类的作用) * @author: liandy * @date: 2019年7月10日 下午11:58:59 * */ public class HelloWorld { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void init(){ System.out.println("init"); } public void destroy() { System.out.println("destroy"); } }
<?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-3.0.xsd"> <bean id="helloWorld" class="cn.com.kamfu.HelloWorld" init-method="init" destroy-method="destroy"> <property name="message" value="Hello World!"/> </bean> </beans>
package cn.com.kamfu;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
// create and configure beans
AbstractApplicationContext context=new ClassPathXmlApplicationContext("*.xml");
HelloWorld helloWorld=context.getBean("helloWorld",HelloWorld.class);
System.out.println(helloWorld.getMessage());
context.registerShutdownHook();
}
}
五、依赖注入
1.setter方法注入
<!-- 声明accountDao对象并交给spring创建 --> <bean name="accountDao" class="com.zejian.spring.springIoc.dao.impl.AccountDaoImpl"/> <!-- 声明accountService对象,交给spring创建 --> <bean name="accountService" class="com.zejian.spring.springIoc.service.impl.AccountServiceImpl"> <!-- 通过setter注入accountDao对象,对象注入使用ref--> <property name="accountDao" ref="accountDao"/> </bean>
2.构造方法注入
<bean name="accountDao" class="com.zejian.spring.springIoc.dao.impl.AccountDaoImpl"/> <!-- 通过构造注入依赖 --> <bean name="accountService" class="com.zejian.spring.springIoc.service.impl.AccountServiceImpl"> <!-- 构造方法方式注入accountDao对象,--> <constructor-arg ref="accountDao"/> </bean>
六、基于注解的配置
/**
* @Title: HelloWorld.java
* @Package cn.com.kamfu
* @Description: TODO(用一句话描述该文件做什么)
* @author: liandy
* @date: 2019年7月10日 下午11:58:59
* @version V1.0
*/
package cn.com.kamfu;
import org.springframework.beans.factory.annotation.Required;
/**
* @ClassName: HelloWorld
* @Description:TODO(这里用一句话描述这个类的作用)
* @author: liandy
* @date: 2019年7月10日 下午11:58:59
*
*/
public class HelloWorld {
private String message;
public String getMessage() {
return message;
}
@Required
public void setMessage(String message) {
this.message = message;
}
public void init(){
System.out.println("init");
}
public void destroy() {
System.out.println("destroy");
}
}
<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> <bean id="helloWorld" class="cn.com.kamfu.HelloWorld" init-method="init"> <!-- <property name="message" value="Hello World!"/> --> </bean> </beans>
package cn.com.kamfu;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
// create and configure beans
AbstractApplicationContext context=new ClassPathXmlApplicationContext("*.xml");
HelloWorld helloWorld=context.getBean("helloWorld",HelloWorld.class);
System.out.println(helloWorld.getMessage());
}
}
七月 11, 2019 1:08:11 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2e817b38: startup date [Thu Jul 11 01:08:11 GMT+08:00 2019]; root of context hierarchy 七月 11, 2019 1:08:11 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from file [D:\workspace\Spring\target\classes\beans.xml] 七月 11, 2019 1:08:11 上午 org.springframework.context.support.ClassPathXmlApplicationContext refresh 警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'helloWorld' defined in file [D:\workspace\Spring\target\classes\beans.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'message' is required for bean 'helloWorld' Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'helloWorld' defined in file [D:\workspace\Spring\target\classes\beans.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'message' is required for bean 'helloWorld' at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:756) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at cn.com.kamfu.App.main(App.java:16) Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'message' is required for bean 'helloWorld' at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:155) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1268) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551) ... 11 more
2.@Autowired:一个属性或者任意命名的可能带有多个参数的方法被用于自动连接 bean。
/** * @Title: Shape.java * @Package cn.com.kamfu * @Description: TODO(用一句话描述该文件做什么) * @author: liandy * @date: 2019年7月11日 上午1:15:28 * @version V1.0 */ package cn.com.kamfu; /** * @ClassName: Shape * @Description:TODO(这里用一句话描述这个类的作用) * @author: liandy * @date: 2019年7月11日 上午1:15:28 * */ public class Shape { private String size; public String getSize() { return size; } public void setSize(String size) { this.size = size; } }
/** * @Title: Paint.java * @Package cn.com.kamfu * @Description: TODO(用一句话描述该文件做什么) * @author: liandy * @date: 2019年7月11日 上午1:16:19 * @version V1.0 */ package cn.com.kamfu; import org.springframework.beans.factory.annotation.Autowired; /** * @ClassName: Paint * @Description:TODO(这里用一句话描述这个类的作用) * @author: liandy * @date: 2019年7月11日 上午1:16:19 * */ public class Paint { private Shape shape; public Shape getShape() { return shape; } @Autowired public void setShape(Shape shape) { this.shape = shape; } public void doSomething() { if(null!=this.shape) { System.out.println("paint:"+this.shape.getClass().getName()); } } }
<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> <bean id="paint" class="cn.com.kamfu.Paint"> </bean> <bean id="shape" class="cn.com.kamfu.Shape"> </bean> </beans>
package cn.com.kamfu; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { // create and configure beans AbstractApplicationContext context=new ClassPathXmlApplicationContext("*.xml"); Paint paint=context.getBean("paint",Paint.class); paint.doSomething(); } }
paint:cn.com.kamfu.Shape
3.@Resource默认按照ByName自动注入,由J2EE提供,需要导入包javax.annotation.Resource。@Resource有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不制定name也不制定type属性,这时将通过反射机制使用byName自动注入策略。
/** * @Title: Shape.java * @Package cn.com.kamfu * @Description: TODO(用一句话描述该文件做什么) * @author: liandy * @date: 2019年7月11日 上午1:15:28 * @version V1.0 */ package cn.com.kamfu; /** * @ClassName: Shape * @Description:TODO(这里用一句话描述这个类的作用) * @author: liandy * @date: 2019年7月11日 上午1:15:28 * */ public class Shape { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
/** * @Title: Paint.java * @Package cn.com.kamfu * @Description: TODO(用一句话描述该文件做什么) * @author: liandy * @date: 2019年7月11日 上午1:16:19 * @version V1.0 */ package cn.com.kamfu; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; /** * @ClassName: Paint * @Description:TODO(这里用一句话描述这个类的作用) * @author: liandy * @date: 2019年7月11日 上午1:16:19 * */ public class Paint { @Resource(name = "circle") private Shape shape; public Shape getShape() { return shape; } public void setShape(Shape shape) { this.shape = shape; } public void doSomething() { if(null!=this.shape) { System.out.println("paint:"+this.shape.getName()); } } }
<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> <bean id="paint" class="cn.com.kamfu.Paint"> </bean> <bean id="shape" name="circle" class="cn.com.kamfu.Shape"> <property name="name" value="circle"></property> </bean> </beans>
package cn.com.kamfu;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
// create and configure beans
AbstractApplicationContext context=new ClassPathXmlApplicationContext("*.xml");
Paint paint=context.getBean("paint",Paint.class);
paint.doSomething();
}
}
七、基于java的配置
@Configuration启动容器+@Bean注册Bean,@Bean下管理bean的生命周期
@Configuration @ComponentScan(basePackages = "com.dxz.demo.configuration") public class TestConfiguration { public TestConfiguration() { System.out.println("TestConfiguration容器启动初始化。。。"); } //@Bean注解注册bean,同时可以指定初始化和销毁方法 @Bean(name="testBean",initMethod="start",destroyMethod="cleanUp") @Scope("prototype") public TestBean testBean() { return new TestBean(); } }
public class TestMain { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); TestBean tb = (TestBean) context.getBean("testBean"); tb.sayHello(); System.out.println(tb); TestBean tb2 = (TestBean) context.getBean("testBean"); tb2.sayHello(); System.out.println(tb2); } }
八、AOP
1.aop的术语
2.通知的类型
(1)Before:在目标方法被调用之前做增强处理,@Before只需要指定切入点表达式即可
(2)AfterReturning:在目标方法正常完成后做增强,@AfterReturning除了指定切入点表达式后,还可以指定一个返回值形参名returning,代表目标方法的返回值
(3)AfterThrowing:主要用来处理程序中未处理的异常,@AfterThrowing除了指定切入点表达式后,还可以指定一个throwing的返回值形参名,可以通过该形参名
来访问目标方法中所抛出的异常对象
(4)After:在目标方法完成之后做增强,无论目标方法时候成功完成。@After可以指定一个切入点表达式
(5)Around:环绕通知,在目标方法完成前后做增强处理,环绕通知是最重要的通知类型,像事务,日志等都是环绕通知,注意编程中核心是一个ProceedingJoinPoint
3.基于注解的aop示例
/** * @Title: Logger.java * @Package cn.com.kamfu * @Description: TODO(用一句话描述该文件做什么) * @author: liandy * @date: 2019年7月12日 上午1:30:26 * @version V1.0 */ package cn.com.kamfu; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; /** * @ClassName: Logger * @Description:TODO(这里用一句话描述这个类的作用) * @author: liandy * @date: 2019年7月12日 上午1:30:26 * */ @Component @Aspect public class Logger { @Pointcut("execution(* cn.com.kamfu.service..*.*(..))") public void pointCut(){} @Before("pointCut()") public void doBefore(JoinPoint joinPoint){ System.out.println("AOP Before Advice..."); } @After("pointCut()") public void doAfter(JoinPoint joinPoint){ System.out.println("AOP After Advice..."); } @AfterReturning(pointcut="pointCut()",returning="returnVal") public void afterReturn(JoinPoint joinPoint,Object returnVal){ System.out.println("AOP AfterReturning Advice:" + returnVal); } @AfterThrowing(pointcut="pointCut()",throwing="error") public void afterThrowing(JoinPoint joinPoint,Throwable error){ System.out.println("AOP AfterThrowing Advice..." + error); System.out.println("AfterThrowing..."); } @Around("pointCut()") public void around(ProceedingJoinPoint pjp){ System.out.println("AOP Aronud before..."); try { pjp.proceed(); } catch (Throwable e) { e.printStackTrace(); } System.out.println("AOP Aronud after..."); } }
/** * @Title: UserService.java * @Package cn.com.kamfu * @Description: TODO(用一句话描述该文件做什么) * @author: liandy * @date: 2019年7月12日 上午1:31:06 * @version V1.0 */ package cn.com.kamfu.service; import org.springframework.stereotype.Service; /** * @ClassName: UserService * @Description:TODO(这里用一句话描述这个类的作用) * @author: liandy * @date: 2019年7月12日 上午1:31:06 * */ @Service public class UserService { public void add(){ System.out.println("UserService add()"); } public boolean delete(){ System.out.println("UserService delete()"); return true; } public void edit(){ System.out.println("UserService edit()"); int i = 5/0; } }
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> <aop:aspectj-autoproxy proxy-target-class="true"/> <context:component-scan base-package="cn.com.kamfu"/> </beans>
package cn.com.kamfu; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.com.kamfu.service.UserService; /** * Hello world! * */ public class App { public static void main( String[] args ) { ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:beans.xml"); UserService userService = (UserService) ctx.getBean("userService"); userService.add(); } }
4.基于xml的aop示例
……
九、JDBC
十、事务管理
十一、MVC框架