Spring的@Autowired问题

Spring2之后,出现很多注解,这些注解让Spring的配置变得混乱起来,因此 ,别人力排Spring的注解。

注解引发的问题:

1、缺乏明确的配置导致程序的依赖注入关系不明确。

2、不利于模块化的装配。

3、给维护带来麻烦,因为你要根据源代码找到依赖关系。

4、通用性不好。如果你哪天抛开了Spring,换了别的Ioc容器,那么你的注解 要一个个的删除。

但是很多傻X级的程序员还偶尔给你用点,或半用半不用,当你问及的时候, 还一本正经的说某某某书上就是这么用的!!!如果你接手他的代码,会很郁闷 。

这里写个例子,为的是看懂带注解的代码,不是推崇注解有多高级,真没必要 。

package lavasoft.springstu.anno;/*** 一个普通的Bean** @author leizhimin 2009-12-23 10:40:38*/public class Foo {         private String name;         public Foo(String name) {                 this.name = name;         }         public String getName() {                 return name;         }         public void setName(String name) {                 this.name = name;         }}

package lavasoft.springstu.anno;import org.springframework.beans.facTory.annotation.Autowired;/*** Spring自动装配的注解** @author leizhimin 2009-12-23 10:41:55*/public class Bar {         @Autowired(required = true)         private Foo foo;         public void f1() {                 System.out.println(foo.getName ());         }}

              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">                                                                               

package lavasoft.springstu.anno;import org.springframework.context.ApplicationContext;import  org.springframework.context.support.ClassPathXmlApplicationContext;/*** 测试自动装配Bean** @author leizhimin 2009-12-23 10:55:35*/public class Test1 {         public static void main(String[] args) {                 ApplicationContext ctx = new  ClassPathXmlApplicationContext("lavasoft/springstu/anno/cfg1.xml");                 Bar bar = (Bar) ctx.getBean ("bar");                 bar.f1();         }}

运行结果:

aaaaProcess finished with exit code 0

从上面的代码中看到,Spring的注解使得配置文件的逻辑很混乱,如果项目中 有大量的类似注解,那维护起来就很困难了。

建议不要使用!

出处:http://lavasoft.blog.51cto.com/62575/247831

即使是不成熟的尝试,也胜于胎死腹中的策略。

Spring的@Autowired问题

相关文章:

你感兴趣的文章:

标签云: