写在前面:spring的两大特点:IOC与aop。IOC(Inverse of Control):控制反转,也可以称为依赖倒置。降低耦合。AOP:即面向切面编程。 从Spring的角度看,AOP最大的用途就在于提供了事务管理的能力。事务管理就是一个关注点,你的正事就是去访问数据库,而你不想管事务(太烦),所以,Spring在你访问数据库之前,自动帮你开启事务,当你访问数据库结束之后,自动帮你提交/回滚事务!
1、spring创建对象的模式是单例模式。简言之调用ac.getBean("mybean");,创建的是同一个对象。
2、创建自己的第一个spring案例:
1、写一个接口:HelloBean
1 public interface HelloBean { 2 public abstract void sayHelloo(); 3 }
2、随意写两个类,继承HelloBean接口,ZNhello与ENhello
public class ENhello implements HelloBean{ @Override public void sayHelloo() { // TODO Auto-generated method stub System.out.println("测试学习spring,接口方式。"); }
public class ZNhello implements HelloBean{ @Override public void sayHelloo() { // TODO Auto-generated method stub System.out.println("测试学习spring,接口方式。 interface"); } }
3、写一个类,调用接口方法:usebean
public class UseBean { private HelloBean w; public void show(){ System.out.println("显示hello的内容:"); w.sayHelloo(); } //set后面的单词英语spring配置文件中的property name="hello" 中的name值一致。 public void sethello(HelloBean hello){ this.w = hello; } }
4、配置spring项目的配置文件:applicationContext.xml
<!-- 创建bean,有指定的id , 对应的class --> <bean id="usetest" class="demo2.UseBean"> <property name="hello" ref="rr"></property> </bean> <bean id="enhellobean" class="demo2.ENhello"> </bean> <bean id="rr" class="demo2.ZNhello"> </bean>
5、测试: Test.java
1 import org.springframework.beans.factory.BeanFactory; 2 import org.springframework.beans.factory.xml.XmlBeanFactory; 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 import org.springframework.context.support.FileSystemXmlApplicationContext; 6 import org.springframework.core.io.ClassPathResource; 7 import org.springframework.core.io.FileSystemResource; 8 import org.springframework.core.io.Resource; 9 10 public class Test { 11 12 private static final String lujingname = "demo2/applicationContext.xml"; 13 14 public static void main(String[] args) { 15 16 // 第一种方式,applicationContext方法 17 //ApplicationContext ac = new ClassPathXmlApplicationContext("demo2/applicationContext.xml"); 18 //UseBean userbean = (UseBean) ac.getBean("usetest"); 19 //userbean.show(); 20 21 // 第二种方式,BeanFactory是applicationContext的父类。 22 //Resource lujing_nei = new ClassPathResource(lujingname); 23 //BeanFactory ac = new XmlBeanFactory(lujing_nei); 24 //UseBean userbean = (UseBean) ac.getBean("usetest"); 25 //userbean.show(); 26 27 //第三种,spring文件直接放在硬盘中的其他位置。 28 ApplicationContext ac = new FileSystemXmlApplicationContext("I:/applicationContext.xml"); 29 //Resource yy = new FileSystemResource("I:/applicationContext.xml"); 30 //BeanFactory ac = new XmlBeanFactory(yy); 31 UseBean userbean = (UseBean) ac.getBean("usetest"); 32 userbean.show(); 33 34 } 35 36 }
6、执行测试,记得是执行运行JAVA测试,而不是执行运行Javaweb的测试……