2011-04-18 118 views
11

嗨, 我在调度类使用弹簧3.0石英。我已经弹簧自动装配工作不

private static final ClassPathXmlApplicationContext applicationContext; 
static { 
    applicationContext = new 
     ClassPathXmlApplicationContext("config/applicationContext.xml"); 
} 

问题创建的应用程序上下文是没有@Autowired豆实际上得到自动有线,所以我必须手动设置的依赖关系是这样的:在哪里

<bean class="com.spr.service.RegistrationServiceImpl" id="registrationService"> 
    <property name="userService" ref="userService" /> 
</bean> 

例子我使用@Autowired表现:

public class RegistrationService { 
    @AutoWired private UserService userService; 
    // setter for userService; 
} 

public class UserService{ 
    // methods 
} 

我也确信,使批注配置在我的Spring配置:

<context:annotation-config/> 
<bean id="registrationSevice" class="RegistrationService"/> 
<bean id="userService" class="UserService"/> 

为什么@Autowired不适合我?

+0

提示:这是一个更好的模式通过构造函数自动装配: '私人最终UserService userService; @Autowired public ResgistrationService(UserService userService){// setter}' – hisdrewness 2011-04-18 01:11:15

回答

22

您没有提供UserService类的源代码,所以我不能确定你的问题。看起来像UserService类缺少'构造型'注释,如@Component或@Service。您还可以使用下列配置春季类路径扫描:

<?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-3.0.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <!-- Add your classes base package here -->   
    <context:component-scan base-package="your.package"/> 

    </beans> 

你豆必须包括春典型化注解等中的一种:

package your.package; 

@Service 
public class UserService{ 
} 
+0

我怀疑是否需要@Service注释,无论如何我会试一试。 – prassee 2011-04-18 03:57:21

+0

@prassee @Component(或sub)Annotation需要为这个类创建一个bean。你也可以用XML来做到这一点,但我相信这不是你想要的 - 或者它? – Ralph 2011-04-18 07:32:17

+0

@Ralph是的。我使用spring mvc 3.0,其中applicationContext.xml具有,控制器使用@controllers注释,依赖对象使用@Autowired Service服务注释。所以我期待在这里。我将与@Service尝试为我服务类 – prassee 2011-04-18 09:10:14

8

Atlast我把它加入了

解决
<context:component-scan base-package="your.package"/> 

在我applicationContext.xml中。谢谢大家的支持。