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());
}
}
<?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>
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();
}
}
運行結果:
aaaa
Process finished with exit code 0
從上面的代碼中看到,Spring的註解是的配置文件的邏輯很混亂,如果項目中有大量的類似註解,那維護起來就很困難了.
建議不要使用!
本文出自 「熔 岩」 博客,請務必保留此出處http://lavasoft.blog.51cto.com/62575/247831
[火星人 ] Java雜談 Spring的註解問題已經有687次圍觀