对象的创建
了解Spring必须得了解一下对象的工厂模式.
Model:
public interface Fruit { public void eat(); }
public class Apple implements Fruit{
public void eat(){ System.out.println("吃苹果"); } }
public class Orange implements Fruit{ public void eat(){ System.out.println("吃桔子"); } }
|
直接创建对象方式:
Fruit fruit = new Orange(); fruit.eat(); |
此方式代码耦合度较高,需要解耦合
工厂方式创建对象
public class FruitFactory { public static Fruit getInstance(int type){ if(type == 1){ return new Apple(); }else if(type == 2){ return new Orange(); } return null; } }
public class Test{
public static void main(String[] args) {
Fruit fruit = FruitFactory.getInstance(2); fruit.eat(); } } |
此方式在一定程序上起到了解耦合的作用,但是还未完全解耦合.
此方式会造成工厂过多的问题出现.
l 利用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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="fruit" class="chapter1.model.Orange"/> </beans>
public class Test{ public static void main(String[] args) { ApplicationContext act = new ClassPathXmlApplicationContext( "applicationContext.xml"); Fruit fruit = (Fruit)act.getBean("fruit"); fruit.eat(); } } |
Spring的出现
Spring涉及到很多领域,请看下图:
我们需要掌握Spring中的技术
l AOP:可以给服务层的方法进行拦截
l Core:Ioc,控制反转,依赖注入
l 事务的配置
Spring是一个超级工厂,能够创建你系统中所需要用到的所有的对象,我们要用对象,需要向Spring这个工厂去索取.
环境的搭建:
用到哪些功能就加载哪些包,比如我现在只用到核心功能IOC这一块,就只需要导入下列包即可.(可以通过MyEclipse自动加载Spring支持的方式加入此包.)
以下为Core功能所需要的几个包
再看一下配置文件的编写
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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
</beans> |
bean的配置:
<bean id="fruit" class="chapter1.model.Orange" />
<bean name="/fruit" class="chapter1.model.Orange" />
id一般用来配置服务层或Dao层
name用来配置Action层,因为需要将导航地址配置在name属性中,name属性允许特殊符号的出现,如”/”