研究了很久新出的 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: Hi
org.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());
}
}
自動探測和注入bean的類:
package org.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class SimpleMan {
// 自動注入名稱為 Man 的 Bean
@Autowired(required = false)
@Qualifier("chineseMan")
//@Qualifier("usMan")
private IMan man;
/**
* @return the man
*/
public IMan getMan() {
return man;
}
/**
* @param man the man to set
*/
public void setMan(IMan man) {
this.man = man;
}
public String hello() {
System.out.println("man.sayHello()=" + man.sayHello());
return "SimpleMan said: Hi";
}
}
一個接口和兩個實現類:
package org.example;
/**
* 抽象的人接口.
* @author BeanSoft
* @version 1.0
*/
public interface IMan {
/**
* 打招呼的抽象定義.
* @return 招呼的內容字符串
*/
public String sayHello();
}
package org.example;
import org.springframework.stereotype.Service;
/**
* 中國人的實現.
* @author BeanSoft
*/
@Service
public class ChineseMan implements IMan {
public String sayHello() {
return "抽你丫的";
}
}
package org.example;
import org.springframework.stereotype.Service;
/**
* @author BeanSoft
* 美國大兵
*/
@Service("usMan")
// 這里定義了一個 id 為 usMan 的 Bean, 標注里面的屬性是 bean 的 id
public class EnglishMan implements IMan {
public String sayHello() {
return this + " said: Fuck you!";
}
}
posted on 2009-06-25 15:06
xzc 閱讀(326)
評論(0) 編輯 收藏 所屬分類:
Spring