??xml version="1.0" encoding="utf-8" standalone="yes"?> 在项目中使用Spring的注解,关于spring的注解,׃U注解方式, Z注释QAnnotationQ的配置有越来越行的趋势,Spring 2.5 应q种势Q提供了(jin)完全Z注释配置 Bean、装?Bean 的功能,(zhn)可以用基于注释的 Spring IoC 替换原来Z XML 的配|。本文通过实例详细讲述?Spring 2.5 Z注释 IoC 功能的用?/p>
注释配置相对?XML 配置h很多的优势:(x) 因此在很多情况下Q注释配|比 XML 配置更受Ƣ迎Q注释配|有q一步流行的势。Spring 2.5 的一大增强就是引入了(jin)很多注释c,现在(zhn)已l可以用注释配|完成大部分 XML 配置的功能。在q篇文章里,我们向(zhn)讲qC用注释进?Bean 定义和依赖注入的内容?/p>
Spring 2.5 引入? Spring 通过一? 在Spring中配|如下:(x) <!-- ?BeanPostProcessor 自动v作用Q对标注 @Autowired ?Bean q行自动注入 --> 按照上面的配|,Spring 直接采?Java 反射机制?Boss 中的 当然Q?zhn)也可以通过 在默认情况下使用 当不能确?Spring 容器中一定拥有某个类?Bean Ӟ可以在需要自动注入该c?Bean 的地方可以? 一般情况下Q? 和找不到一个类型匹?Bean 相反的一个错误是Q如?Spring 容器中拥有多个候?BeanQSpring 容器在启动时也会(x)抛出 Spring 允许我们通过 Ҏ(gu)员变量进行注释:(x) Ҏ(gu)员变量?@Qualifier 注释 Ҏ(gu)造函数入参进行注释:(x) Spring 不但支持自己定义? Resource 注释cM?Spring 发布包的 lib/j2ee/common-annotations.jar cd中,因此在用之前必d其加入到目的类库中。来看一个? 一般情况下Q我们无需使用cM? 要让 JSR-250 的注释生效,除了(jin)?Bean cM标注q些注释外,q需要在 Spring 容器中注册一个负责处理这些注释的 Spring 容器中的 Bean 是有生命周期的,Spring 允许?Bean 在初始化完成后以?Bean 销毁前执行特定的操作,(zhn)既可以通过实现 InitializingBean/DisposableBean 接口来定制初始化之后 / 销毁之前的操作Ҏ(gu)Q也可以通过 <bean> 元素?init-method/destroy-method 属性指定初始化之后 / 销毁之前调用的操作Ҏ(gu)。关?Spring 的生命周期,W者在《精?Spring 2.x—企业应用开发精解》第 3 章进行了(jin)详细的描qͼ有兴的读者可以查阅?/p>
JSR-250 为初始化之后/销毁之前方法的指定定义?jin)两个注释类Q分别是 @PostConstruct ?@PreDestroyQ这两个注释只能应用于方法上。标注了(jin) @PostConstruct 注释的方法将在类实例化后调用Q而标注了(jin) @PreDestroy 的方法将在类销毁之前调用?/p>
(zhn)只需要在Ҏ(gu)前标? 我们知道Q不是通过实现 通过以下的测试代码,(zhn)将可以看到 Bean 的初始化 / 销毁方法是如何被执行的Q?/p>
q时Q?zhn)看到标注?jin) 使用 <context:annotation-config/> 化配|?/span> Spring 2.1 d?jin)一个新?context ?Schema 命名I间Q该命名I间Ҏ(gu)释驱动、属性文件引入、加载期l入{功能提供了(jin)便捷的配|。我们知道注释本w是不会(x)做Q何事情的Q它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作h? 而我们前面所介绍? <context:annotationconfig/> 隐式地?Spring 容器注册 在配|文件中使用 context 命名I间之前Q必d <beans> 元素中声?context 命名I间?/p>
虽然我们可以通过 下面Q我们完全用注释定?Bean q完?Bean 之间装配Q?/p>
仅需要在cd义处Q? q样Q我们就可以?Boss cM通过 在? q里Q所有通过 <bean> 元素定义 Bean 的配|内容已l被U除Q仅需要添加一?<context:component-scan/> 配置px(chng)有问题(sh)(jin)——Spring XML 配置文g得到?jin)极致的化(当然配置元数据还是需要的Q只不过以注释Ş式存在Ş?jin)?j)?lt;context:component-scan/> ?base-package 属性指定了(jin)需要扫描的cdQ类包及(qing)光归子包中所有的c都?x)被处理?/p>
<context:component-scan/> q允许定义过滤器基包下的某些类U_或排除。Spring 支持以下 4 U类型的qo(h)方式Q通过下表说明Q?/p>
下面是一个简单的例子Q?/p>
值得注意的是 <context:component-scan/> 配置不但启用了(jin)对类包进行扫描以实施注释驱动 Bean 定义的功能,同时q启用了(jin)注释驱动自动注入的功能(卌隐式地在内部注册? 默认情况下通过 q样Q当?Spring 容器中获? Spring 2.5 中除?jin)提? 是否有了(jin)q些 IOC 注释Q我们就可以完全摒除原来 XML 配置的方式呢Q答案是否定的。有以下几点原因Q?/p>
所以在实现应用中,我们往往需要同时用注释配|和 XML 配置Q对于类U别且不?x)发生变动的配置可以优先考虑注释配置Q而对于那些第三方cM?qing)容易发生调整的配置则应优先考虑使用 XML 配置。Spring ?x)在具体实?Bean 创徏?Bean 注入之前这两种配置方式的元信息融合在一赗?/p>
Spring ?2.1 以后Ҏ(gu)释配|提供了(jin)强力的支持,注释配置功能成ؓ(f) Spring 2.5 的最大的亮点之一。合理地使用 Spring 2.5 的注释配|,可以有效减少配置的工作量Q提高程序的内聚性。但是这q不意味着传统 XML 配置走向消亡,在第三方c?Bean 的配|,以及(qing)那些诸如数据源、缓存池、持久层操作模板cR事务管理等内容的配|上QXML 配置依然拥有不可替代的地位?/p>
有一天皇帝想宠幸某个女Q于是跟太监_(d)今夜我要宠幸女 而皇帝爽M(jin)Q什么都不用,交给太监d理,控制权{Ud太监手中M(jin)而不是皇帝,
<!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- include java script once we verify teams wants to use this and it will work on dbcs and cyrillic characters --><!--END RESERVED FOR FUTURE USE INCLUDE FILES-->
@Autowired
注释Q它可以对类成员变量、方法及(qing)构造函数进行标注,完成自动装配的工作?/p>
BeanPostProcessor
?@Autowired
q行解析Q所以要?@Autowired
起作用必M先在 Spring 容器中声?AutowiredAnnotationBeanPostProcessor
Bean?/p>
<bean class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>
?Spring 容器启动ӞAutowiredAnnotationBeanPostProcessor
扫?Spring 容器中所?BeanQ当发现 Bean 中拥?@Autowired
注释时就扑ֈ和其匚wQ默认按cd匚wQ的 BeanQƈ注入到对应的地方中去?/p>
car
?office
q两个私有成员变量进行自动注入。所以对成员变量使用 @Autowired
后,(zhn)大可将它们?setter Ҏ(gu)Q?code>setCar() ?setOffice()
Q从 Boss 中删除?/p>
@Autowired
Ҏ(gu)法或构造函数进行标注,@Autowired
注释q行自动注入ӞSpring 容器中匹配的候?Bean 数目必须有且仅有一个。当找不C个匹配的 Bean ӞSpring 容器抛?BeanCreationException
异常Qƈ指出必须臛_拥有一个匹配的 Bean?/p>
@Autowired(required = false)
Q这{于告诉 SpringQ在找不到匹?Bean 时也不报错?/p>
@Autowired
的地斚w是需要注?Bean 的,使用?jin)自动注入而又允许不注入的情况一般仅?x)在开发期或测试期到Q如Z(jin)快速启?Spring 容器Q仅引入一些模块的 Spring 配置文gQ,所?@Autowired(required = false)
?x)很用到?/p>
BeanCreationException
异常?/p>
@Qualifier
注释指定注入 Bean 的名Uͼq样歧义消除了(jin)Q可以通过下面的方法解军_常:(x)
清单 13. 使用 @Qualifier 注释指定注入 Bean 的名U?/strong>
@Autowired
public void setOffice(@Qualifier("office")Office office) {
this.office = office;
}
@Qualifier("office")
中的 office
?Bean 的名Uͼ所?@Autowired
?@Qualifier
l合使用Ӟ自动注入的策略就?byType 转变?byName ?jin)?code>@Autowired 可以Ҏ(gu)员变量、方法以?qing)构造函数进行注释,?@Qualifier
的标注对象是成员变量、方法入参、构造函数入参。正是由于注释对象的不同Q所?Spring 不将 @Autowired
?@Qualifier
l一成一个注释类。下面是Ҏ(gu)员变量和构造函数入参进行注释的代码Q?/p>
public class Boss {
@Autowired
private Car car;
@Autowired
@Qualifier("office")
private Office office;
…
}
清单 15. Ҏ(gu)造函数变量?@Qualifier 注释
public class Boss {
private Car car;
private Office office;
@Autowired
public Boss(Car car , @Qualifier("office")Office office){
this.car = car;
this.office = office ;
}
}
@Qualifier
只能?@Autowired
l合使用Q是?@Autowired
有益的补充。一般来Ԍ@Qualifier
Ҏ(gu)法签名中入参q行注释?x)降低代码的可读性,而对成员变量注释则相对好一些?/p>
@Autowired
的注释,q支持几个由 JSR-250 规范定义的注释,它们分别?@Resource
?code>@PostConstruct 以及(qing) @PreDestroy
?/p>
@Resource
的作用相当于 @Autowired
Q只不过 @Autowired
?byType 自动注入Q面 @Resource
默认?byName 自动注入|了(jin)?code>@Resource 有两个属性是比较重要的,分别?name ?typeQSpring ?@Resource
注释?name 属性解析ؓ(f) Bean 的名字,?type 属性则解析?Bean 的类型。所以如果?name 属性,则?byName 的自动注入策略,而?type 属性时则?byType 自动注入{略。如果既不指?name 也不指定 type 属性,q时通过反射机制使用 byName 自动注入{略?/p>
@Resource
的例子:(x)
清单 16. 使用 @Resource 注释?Boss.java
package com.baobaotao;
import javax.annotation.Resource;
public class Boss {
// 自动注入cd?Car ?Bean
@Resource
private Car car;
// 自动注入 bean 名称?office ?Bean
@Resource(name = "office")
private Office office;
}
@Resource(type=Car.class)
的注释方式,因ؓ(f) Bean 的类型信息可以通过 Java 反射从代码中获取?/p>
BeanPostProcessor
Q?/p>
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
CommonAnnotationBeanPostProcessor
实现?BeanPostProcessor
接口Q它负责扫描使用?JSR-250 注释?BeanQƈ对它们进行相应的操作?/p>
清单 17. 使用 @PostConstruct ?@PreDestroy 注释?Boss.java
package com.baobaotao;
import javax.annotation.Resource;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class Boss {
@Resource
private Car car;
@Resource(name = "office")
private Office office;
@PostConstruct
public void postConstruct1(){
System.out.println("postConstruct1");
}
@PreDestroy
public void preDestroy1(){
System.out.println("preDestroy1");
}
…
}
@PostConstruct
?@PreDestroy
Q这些方法就?x)?Bean 初始化后或销毁之前被 Spring 容器执行?jin)?/p>
InitializingBean
/DisposableBean
接口Q还是通过 <bean> 元素?init-method/destroy-method
属性进行配|,都只能ؓ(f) Bean 指定一个初始化 / 销毁的Ҏ(gu)。但是?@PostConstruct
?@PreDestroy
注释却可以指定多个初始化 / 销毁方法,那些被标?@PostConstruct
?@PreDestroy
注释的方法都?x)在初始?/ 销毁时被执行?/p>
package com.baobaotao;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnoIoCTest {
public static void main(String[] args) {
String[] locations = {"beans.xml"};
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(locations);
Boss boss = (Boss) ctx.getBean("boss");
System.out.println(boss);
ctx.destroy();// 关闭 Spring 容器Q以触发 Bean 销毁方法的执行
}
}
@PostConstruct
?postConstruct1()
Ҏ(gu)在 Spring 容器启动Ӟ创徏 Boss
Bean 的时候被触发执行Q而标注了(jin) @PreDestroy
注释?preDestroy1()
Ҏ(gu)在 Spring 容器关闭前销?Boss
Bean 的时候被触发执行?/p>
回页?/span>
AutowiredAnnotationBeanPostProcessor
?CommonAnnotationBeanPostProcessor
是处理q些注释元数据的处理器。但是直接在 Spring 配置文g中定义这?Bean 昑־比较W拙。Spring 为我们提供了(jin)一U方便的注册q些 BeanPostProcessor
的方式,q就?<context:annotation-config/>。请看下面的配置Q?/p>
<?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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config/>
<bean id="boss" class="com.baobaotao.Boss"/>
<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="001"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" U旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
AutowiredAnnotationBeanPostProcessor
?code>CommonAnnotationBeanPostProcessor?code>PersistenceAnnotationBeanPostProcessor 以及(qing) equiredAnnotationBeanPostProcessor
q?4 ?BeanPostProcessor?/p>
回页?/span>
@Autowired
?@Resource
?Bean cM使用自动注入功能Q但?Bean q是?XML 文g中通过 <bean> q行定义 —?也就是说Q在 XML 配置文g中定?BeanQ通过 @Autowired
?@Resource
?Bean 的成员变量、方法入参或构造函数入参提供自动注入的功能。能否也通过注释定义 BeanQ从 XML 配置文g中完全移?Bean 定义的配|呢Q答案是肯定的,我们通过 Spring 2.5 提供?@Component
注释可以达到这个目标了(jin)?/p>
清单 20. 使用 @Component 注释?Car.java
package com.baobaotao;
import org.springframework.stereotype.Component;
@Component
public class Car {
…
}
@Component
注释可以将一个类定义?Spring 容器中的 Bean。下面的代码?Office
定义Z?BeanQ?/p>
清单 21. 使用 @Component 注释?Office.java
package com.baobaotao;
import org.springframework.stereotype.Component;
@Component
public class Office {
private String officeNo = "001";
…
}
@Autowired
注入前面定义?Car
?Office Bean
?jin)?/p>
清单 22. 使用 @Component 注释?Boss.java
package com.baobaotao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component("boss")
public class Boss {
@Autowired
private Car car;
@Autowired
private Office office;
…
}
@Component
有一个可选的入参Q用于指?Bean 的名Uͼ?Boss 中,我们将 Bean 名称定义?#8220;boss
”。一般情况下QBean 都是 singleton 的,需要注?Bean 的地方仅需要通过 byType {略可以自动注入了(jin)Q所以大可不必指?Bean 的名U?/p>
@Component
注释后,Spring 容器必须启用cL描机制以启用注释驱动 Bean 定义和注释驱?Bean 自动注入的策略。Spring 2.5 ?context 命名I间q行?jin)扩展,提供了(jin)这一功能Q请看下面的配置Q?/p>
<?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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.baobaotao"/>
</beans>
qo(h)器类?/th>
说明
注释
假如 com.baobaotao.SomeAnnotation 是一个注释类Q我们可以将使用该注释的c过滤出来?/td>
cd指定
通过全限定类名进行过滤,如?zhn)可以指定?com.baobaotao.Boss U_扫描Q而将 com.baobaotao.Car 排除在外?/td>
正则表达?/td>
通过正则表达式定义过滤的c,如下所C:(x) com\.baobaotao\.Default.*
AspectJ 表达?/td>
通过 AspectJ 表达式定义过滤的c,如下所C:(x) com. baobaotao..*Service+
<context:component-scan base-package="com.baobaotao">
<context:include-filter type="regex"
expression="com\.baobaotao\.service\..*"/>
<context:exclude-filter type="aspectj"
expression="com.baobaotao.util..*"/>
</context:component-scan>
AutowiredAnnotationBeanPostProcessor
?CommonAnnotationBeanPostProcessor
Q,因此当?<context:component-scan/> 后,可以将 <context:annotation-config/> U除?jin)?/p>
@Component
定义?Bean 都是 singleton 的,如果需要用其它作用范围的 BeanQ可以通过 @Scope
注释来达到目标,如以下代码所C:(x)
清单 24. 通过 @Scope 指定 Bean 的作用范?/strong>
package com.baobaotao;
import org.springframework.context.annotation.Scope;
…
@Scope("prototype")
@Component("boss")
public class Boss {
…
}
boss
Bean Ӟ每次q回的都是新的实例了(jin)?/p>
回页?/span>
@Component
注释外,q定义了(jin)几个拥有Ҏ(gu)语义的注释,它们分别是:(x)@Repository
?code>@Service ?@Controller
。在目前?Spring 版本中,q?3 个注释和 @Component
是等效的Q但是从注释cȝ命名上,很容易看?gu)?3 个注释分别和持久层、业务层和控制层QWeb 层)(j)相对应。虽然目前这 3 个注释和 @Component
相比没有什么新意,?Spring 在以后的版本中为它们添加特D的功能。所以,如果 Web 应用E序采用?jin)经典的三层分层l构的话Q最好在持久层、业务层和控制层分别采用 @Repository
?code>@Service ?@Controller
对分层中的类q行注释Q而用 @Component
寚w些比较中立的c进行注释?/p>
回页?/span>
JdbcTemplate
?code>SessionFactoryBean {)(j)Q注释配|将无法实施Q此?XML 配置是唯一可用的方式?@Transaction
事务注释Q?aop/tx 命名I间的事务配|更加灵zd单?
回页?/span>
皇帝往往不会(x)告诉太监Q今晚几点会(x)回宫Q会(x)回哪张龙床,他只?x)告诉太监他要哪位美?/font>
其它一切都交由太监d排,C(jin)晚上皇帝回宫Ӟ自然?x)有女出现在皇帝的龙床?
q就是控制反转,而把女送到皇帝的寝宫里面去是注射
太监是是框枉面的注射控制器类BeanFactoryQ负责找到美奛_ƈ送到龙床上去
整个后宫可以看成是Spring框架Q美奛_是Spring控制下的JavaBean
N班,帮助l介l一个云云,于是领班开始给他张|?br />
介绍一个合适的l他Q完事后Q再把小姐还l领班,下次再来
q个q程中,领班是查询上下文ContextQ领班的一个职能就是给客户扑ֈ他们所要的姐
q就是lookup()Ҏ(gu)Q领班手中的姐名录是JNDI//Java Naming and Directory Interface
姐是EJBQ?font color="#0000ff">饥(f)h客户?/font>Q?font color="#ff0000">青楼是EJB容器
看到区别?jin)么Q?/font>
]]>
]]>
ȝ来看 Java EE 5 的标注开发方式开来是得到?jin)大家的认可?
@Service 相当于定?bean, 自动Ҏ(gu) bean 的类名生成一个首字母写?bean
@Autowired 则是自动注入依赖的类, 它会(x)在类路径中找成员对应的类/接口的实现类, 如果扑ֈ多个, 需要用 @Qualifier("chineseMan") 来指定对应的 bean ?ID.
一定程度上大大化了(jin)代码的编? 例如一对一?bean 映射现在完全不需要写M额外?bean 定义?
下面是代码的q行l果:
man.sayHello()=你好
SimpleMan said: Hi
org.example.EnglishMan@12bcd4b said: Hello
代码:
beans.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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config/> <context:component-scan base-package="org.example"/> </beans>
试c?
import org.example.IMan;
import org.example.SimpleMan;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
SimpleMan dao = (SimpleMan) ctx.getBean("simpleMan");
System.out.println(dao.hello());
IMan man = (IMan) ctx.getBean("usMan");
System.out.println(man.sayHello());
}
}
自动探测和注入bean的类:
package org.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class SimpleMan {
// 自动注入名称?Man ?Bean
@Autowired(required = false)
@Qualifier("chineseMan")
//@Qualifier("usMan")
private IMan man;
/**
* @return the man
*/
public IMan getMan() {
return man;
}
/**
* @param man the man to set
*/
public void setMan(IMan man) {
this.man = man;
}
public String hello() {
System.out.println("man.sayHello()=" + man.sayHello());
return "SimpleMan said: Hi";
}
}
一个接口和两个实现c?
package org.example;
/**
* 抽象的h接口.
* @author BeanSoft
* @version 1.0
*/
public interface IMan {
/**
* 打招呼的抽象定义.
* @return 招呼的内容字W串
*/
public String sayHello();
}
package org.example;
import org.springframework.stereotype.Service;
/**
* 中国人的实现.
* @author BeanSoft
*/
@Service
public class ChineseMan implements IMan {
public String sayHello() {
return "你好";
}
}
package org.example;
import org.springframework.stereotype.Service;
/**
* @author BeanSoft
*
*/
@Service("usMan")
// q里定义?jin)一?id ?usMan ?Bean, 标注里面的属性是 bean ?id
public class EnglishMan implements IMan {
public String sayHello() {
return this + " said: Hello!";
}
}
首先惌?/span>IoCInversion of ControlspringIoCspringspring对象间的关系。这是什么意思呢QD个简单的例子Q我们是如何扑֥朋友的?常见的情冉|Q我们到处去看哪里有长得漂亮w材又好?/span>mm好?/span>qqipiq……………l的E序开发也是如此,在一个对象中Q如果要使用另外的对象,必d到它Q自?/span>newJNDI?/span>ConnectionIoC介提Z个列表,告诉它我x(chng)个什么样的女朋友Q比如长得像李嘉ƣ,w材像林熙雷Q唱歌像周杰伦,速度像卡z斯Q技术像齐达内之cȝQ然后婚介就?x)按照?/span>mmӞ而是有婚介这样一个类似容器的机构来控制?/span>Springspringspring么东西,你需要什么东西,然后spring springspring都被springIoCDIDependency InjectionAAConnection springspringAConnectionConnectionAq行ӞspringConnectionAA ConnectionConnectionspringADI Java 1.3reflectionspringjava doc
BromonIoCDIexpert one-on-one J2EE Development without EJBIoC: EJBApache AvalonJavaJavaBeanJavaBeanSetter InjectionConstructor Injection IoCDISpringJavaBeanSpringnewSpringIoC?/span>expert one-on-one J2EE Development without EJBSpringDemoSpringSpringSpringSpring spring-framework-1.2.6-with-dependencies.zipspring-framework-1.2.6.zipspring-framework-1.2.6-with-dependencies.zipspring-framework-1.2.6-with-dependencies.ziphttp://prdownloads.sourceforge.net/springframework/spring-framework-1.2.6-with-dependencies.zipjarSpringspring-core.jarspring-framework-1.2.6"disteclipseloglog4j-1.2.9.jarspring-framework-1.2.6"lib"log4jcommons-logging.jarspring-framework-1.2.6"lib"jakarta-commonsDemo <!--[if !supportLists]-->1?/span><!--[endif]-->log4j.propertieslog4j.rootLogger=Debug, stdout Log4jLog4J<!--[if !supportLists]-->2?/span><!--[endif]-->HelloBeanpackage com; JavaBeanStringhelloworld"Hello!World!"<!--[if !supportLists]-->3?/span><!--[endif]-->Bean.xml<?xml version="1.0" encoding="GBK"?> Spirng重点之一是配置文gQ上面是个相当简单的配置文gQ我惛_安应该看得懂。最后就是写应用E序?jin)?/span> 4?/span><!--[endif]-->Test的代码:(x)
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n
public class HelloBean {
private String helloworld="Hello!World!";
public String getHelloworld() {
return helloworld;
}
public void setHelloworld(String helloworld) {
this.helloworld = helloworld;
}
}
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="helloBean" class="com.HelloBean">
<property name="helloworld">
<value>Hello!Rick</value>
</property>
</bean>
</beans>
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
//实例化JavaBeanQ主要是Z(jin)比较new对象和依赖注入两者的区别
HelloBean hellobean=new HelloBean();
System.out.println(hellobean.getHelloworld());
//通过Spring讉KJavaBeanlg
Resource resource=new ClassPathResource("com/bean.xml");
BeanFactory factory=new XmlBeanFactory(resource);
hellobean=(HelloBean)factory.getBean("helloBean");
System.out.println(hellobean.getHelloworld());
}
}
Spring的依赖注入相对复杂一点,主要是明白调用别的BeanQ不是通过实例化对象来调用Q而是告诉SpringQ我需要什么BeanQ然后Spring再向你的Bean里面注入你所需要的Bean对象?br />
接下来说说代码实玎ͼ我只是在刚刚的例子上再添加一点东东?br />
首先要增加一个HelloImp的接口,q是问什么呢Q那你得问SpringQ它定的规矩QJavaBean的实现要有两个部分,一个接口,一个默认实现。你不照做就不行?br />
HelloImp代码Q?nbsp;
public interface HelloImp {
public void getName();
}
实现HelloImp的Hello代码Q?br />
public class Hello implements HelloImp {
public void getName(){
System.out.println("Jack");
}
}
HelloBeanHelloSpringpackage com;
public class HelloBean {
private String helloworld="Hello!World!";
private HelloImp hello; //注意q个U有对象是借口
public String getHelloworld() {
return helloworld;
}
public void setHelloworld(String helloworld) {
this.helloworld = helloworld;
}
public void setHello(HelloImp hello) {
this.hello = hello;
}
public void get(){
this.hello.getName();
}
}
配置文g也需要增加一点东西:(x)
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!—注意引用的cL具体的类Hello-->
<bean id="myHello" class="com.Hello">
</bean>
<bean id="helloBean" class="com.HelloBean">
<property name="helloworld">
<value>Hello!Rick</value>
</property>
<property name="hello">
<ref bean="myHello"></ref>
</property>
</bean>
</beans>
注意字体加粗的部分?br />
Testhellobean.get();package com;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
HelloBean hellobean=new HelloBean();
System.out.println(hellobean.getHelloworld());
Resource resource=new ClassPathResource("com/bean.xml");
BeanFactory factory=new XmlBeanFactory(resource);
hellobean=(HelloBean)factory.getBean("helloBean");
System.out.println(hellobean.getHelloworld());
hellobean.get();
}
}
到这QSpring的IoC和DIȝ有了(jin)一定的认识Q也是敲开?jin)Spring的大门了(jin)?br />
]]>