Spring 入门的第一个例子
1、Spring的实现原理和现实工厂原理是一样。可以理解成Spring就是一个大的工厂。
?
?
2、我先写一个简单工厂,然后再写一个Spring对比一下。
?
?
3、简单工厂例子如下:
????? 3.1、先写一个接口。
????? public interface Ren {
???? ?public? void say();
????? }
?
???? 3.2、在写两个实现类。
???????public class Man implements Ren {
?????? public void say() {
?????? System.out.println("男人在说话!");
???? ?}
? }?
?
?????? public class Woman implements Ren {
?????? public void say() {
?????? System.out.println("女人在说话!");
???? ?}
? }
?
?? 3.3、写一个工厂类,主要用来得到类的实例,也就是初始化类。
?????????? 下面做了个判断,主要是在下面测试类里面用。
?
???? public class RenFactory {
????? public static Ren getRenInstance(String s){
??? ?Ren r=null;
??? ?if(s=="W"){
??? ??r=new Woman();
???? ?}else if(s=="M"){
??? ??r=new Man();
? ? ?}
??return r;
? ?}
? }
?
??? 3.4、写一个测试类,
?????????? 当输入“M”,会初始化Man;
??????????? 当输入“W”,会初始化Woman;
?
???? ?public class TestRen {
? ?? ?public static void main(String[] args){
??????? Ren f=RenFactory.getRenInstance("M");//类名可以直接调用类里面的静态方法。
??????? f.say();
?? }
}
?
所以:输出结果是“男人在说话”。
?
上面就是一个简单工厂的实现。
?
4、下面我用Spring实现上面的功能
?
??? 4.1、先写一个接口。
????? public interface Ren {
???? ?public? void say();
????? }
?
???? 4.2、在写两个实现类。
???????public class Man implements Ren {
?????? public void say() {
?????? System.out.println("男人在说话!");
???? ?}
? }?
?
?????? public class Woman implements Ren {
?????? public void say() {
?????? System.out.println("女人在说话!");
???? ?}
? }
?
?? 4.3、Spring操作类的写法
??????
?????? import org.springframework.context.ApplicationContext;
?????? import org.springframework.context.support.ClassPathXmlApplicationContext;
?
????? public class TestRenSpring {
????? public static void main(String[] args){
????? ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
????? Ren r=(Ren)context.getBean("w");
????? r.say();
????? }
? }
?
? 4.4、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-2.5.xsd">
?
?
???? <bean id="w" class="org.Spring.com.Man"></bean>
</beans>
????????
?
? 总结比较:相当于把工厂类换成了Spring的配置文件。这样写有什么好处吗?当然有了,今后要想改动就只改配置文件就可以了。不用动后台类了。这样更容易维护吧。
??? TestRen与TestRenSpring测试类其实是,他们属于前台。有客户自己输入值。我们只修改配置文件就可以了。
?
?