如何在Spring框架中使用注解初始化java bean?

问题描述:

我有一个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; –

我相信这是因为你必须启用包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

您需要添加

<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

''做所有事情''还有更多!如果您已经包含组件扫描,则不需要。 –

你不应该需要有两个声明。

使用情境:注解配置允许通过注释等

使用情境豆自动装配:组件扫描提供一切方面:注解的配置,但允许豆的自动发现。您在上下文中提供的软件包:component-scan将扫描该软件包和所有子软件包。

希望这有助于

  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. 构造的上方。