天天看点

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) { 

}

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()); 

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

        <!-- 引用@Autowired必须定义这个bean --> 

        <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 

        <!-- 通过构造方法装配的Bean --> 

        <bean id="foo" class="lavasoft.springstu.anno.Foo"> 

                <constructor-arg index="0" type="java.lang.String" value="aaaa"/> 

        </bean> 

        <!-- 通过注解装配的Bean,我还以为它和Foo没关系呢 --> 

        <bean id="bar" class="lavasoft.springstu.anno.Bar"/> 

</beans>

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(); 

运行结果:

aaaa 

Process finished with exit code 0

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