2011-09-18 248 views
-1

我有一個Java bean:如何在Spring框架中使用註解初始化java bean?

public class User{ 

    private Integer userid; 

    private String username; 

    private String password; 

    private boolean enable; 

    //getter and setter 

} 

我能夠在它的context.xml通過初始化爲一個Spring bean:

<context:component-scan base-package="com.myCompany.myProject" /> 

但我不希望它初始化在xml中。我怎樣才能用sring 3註解來初始化它。我試着用下面的方法:

@Component 
public class User{ 

    private Integer userid; 

    private String username; 

    private String password; 

    private boolean enable; 

    //getter and setter 

} 

但是上面的不適合我。有任何想法嗎?

+0

我相信你的意思是'instantiate'而不是'initialize'? – Saket

+0

什麼不起作用?你想在哪裏使用這個'User'類? –

+0

我正在嘗試在控制器上使用用戶,如 @Autowierd public class LoginController private user user; –

回答

0

我相信這是因爲你必須啓用包com.myCompany.myProject組件掃描,而不是在包裝上com.myCompany.myProject.db

更改掃描定義這樣:<context:component-scan base-package="com.myCompany.myProject.db" />(或添加一個新的,如果你從另一個想要班包也是如此),您可以從XML中刪除bean定義,併爲您的註釋工作。

愚蠢,但仍然確保@Component註釋是Spring的註釋。我有時會面臨這樣一個愚蠢的問題:定義一個實際上不是來自所需庫的註釋(由於註釋的相同名稱,我的類路徑中的不同庫)。

+1

我相信'base-package'屬性也應該選擇子包。 –

+0

'base-package'是根。所有的子軟件包將被掃描。請參閱http://static.springsource.org/spring/docs/current/spring-framework-reference/html/beans.html#beans-classpath-scanning – micfra

0

您需要添加

<context:annotation-config /> 

與該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:p="http://www.springframework.org/schema/p" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:aop="http://www.springframework.org/schema/aop" 
xsi:schemaLocation=" 
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> 
<context:annotation-config /> 
<context:component-scan base-package="com.vanilla.example"></context:component-scan> 
</beans> 
+0

''做所有事情''還有更多!如果您已經包含組件掃描,則不需要。 –

0

你不應該需要有兩個聲明。

使用情境:註解配置允許通過註釋等

使用情境豆自動裝配:組件掃描提供一切方面:註解的配置,但允許豆的自動發現。您在上下文中提供的軟件包:component-scan將掃描該軟件包和所有子軟件包。

希望這有助於

0
  1. 確保「用戶」類包裝或 「com.myCompany.myProject」的子包。

  2. 您不需要包含<context: annotation-config/>,它包含在組件掃描中的 。

  3. 這個bean是一個名爲「用戶」默認情況下,除非你 @Component來指定bean名稱(「myBeanName」)

一旦做到這一點,就可以自動裝配豆到另一種:

@Autowired 
User user; 

OR

@Inject 
User user; 

NOT ES:
@Inject是不需要注入的javax.inject註釋。
@Autowired是Spring註釋,並且需要注入。
@Autowired可以以下列方式之一被使用:

  1. 只是接受用戶豆
  2. 設定部接受用戶豆成員變量
  3. 構造的上方。
相關問題