Spring 2.5标注开发的简单例子2011-09-14研究了很久新出的 Spring 2.5, 总算大致明白了如何用标注定义 Bean, 但是如何定义和注入类型为 java.lang.String 的 bean 仍然未解决, 希望得到高人帮助.总的来看 Java EE 5 的标注开发方式开来是得到了大家的认可了.@Service 相当于定义 bean, 自动根据 bean 的类名生成一个首字母小写的 bean@Autowired 则是自动注入依赖的类, 它会在类路径中找成员对应的类/接口的实现类, 如果找到多个, 需要用 @Qualifier("chineseMan") 来指定对应的 bean 的 ID.一定程度上大大简化了代码的编写, 例如一对一的 bean 映射现在完全不需要写任何额外的 bean 定义了.下面是代码的运行结果:
man.sayHello()=抽你丫的SimpleMan said: Hiorg.example.EnglishMan@12bcd4b said: Fuck you!
代码: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>
测试类:
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()); }}