天天看點

Spring之@Autowired問題

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的注解使得配置檔案的邏輯很混亂,如果項目中有大量的類似注解,那維護起來就很困難了。

建議不要使用!

繼續閱讀