0

我有一个弹簧休息应用程序,它有Rest Controller如下

@RestController
public class IngestorController
{
    @Autowired
    private IngestorService ingestorService;

    @RequestMapping( value = "/ingestor/createAndDeploy/{ingestorName}", method = RequestMethod.POST )
    public void createAndDeploy( @PathVariable String ingestorName )
    {
        ingestorService.createAndDeploy( ingestorName );
    }

}

同样,我有一个Service Bean如下

@Service
public class IngestorService
{
    @Autowired
    private IngestorCommandBuilder ingestorCommandBuilder;

    private String uri;
    private DeployTemplate deployTemplate;

    public void init() throws URISyntaxException
    {
        deployTemplate = new DeployTemplate( new URI( uri ) );
    }

    @Transactional
    public void createAndDeploy( Ingestor ingestor )
    {
         //.....
     }

}

我有Spring config如下所示

<bean id="ingestorCommandBuilder" class="org.amaze.server.ingestor.IngestorCommandBuilder" />

<bean id="ingestorService" class="org.amaze.server.service.IngestorService" init-method="init">
    <property name="uri" value="http://localhost:15217" />
</bean>

<bean id="ingestorController" class="org.amaze.server.controller.IngestorController"/>

每当我尝试启动应用程序上下文时,应用程序上下文就会启动,它会触发 IngestorService 中的 init 方法,deployTemplate 对象也会为服务 bean 初始化。

但是这个 bean 不是为 IngestorController 自动装配的。当我从邮递员点击其余端点时,服务 bean 的 deployTemplate 属性为 null。分配给 Controller 中的 ingestorService 变量的对象是另一个对象,而不是为 init 方法调用的对象...

我尝试将服务 bean 设为单例(即使默认范围是单例)但 dint 工作......

我无法找出我正在做的错误..任何建议表示赞赏...

4

3 回答 3

0

如果您使用基于注释的配置,您通常不需要在应用程序上下文 xml 文件中描述所有 bean。注释是自动装配服务所需的全部内容。

要正确定义您的 init 方法,请使用@PostConstruct注释。属性可以很容易地移动到 externat .properties 文件并通过@Value注释注入到您的代码中。

或者,使用@Qualifierwith @Autowired

于 2015-06-23T04:57:52.380 回答
0

首先确保您拥有:

<context:annotation-config />

在你的 Spring 配置中。现在您有多种选择:

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

扫描组件,或

<!-- autowiring byName, bean name should be same as the property name annotate your ingestorservice with @Service("ingestorServiceByName") -->
<bean name="ingestorServiceByName" class="your.package.com.IngestorService" autowire="byName" />

<!-- autowiring byType, tif there are more bean of the same "general" type, this will not work and you will have to use qualifier or mark one bean as @Primary  -->
<bean name="ingestorServiceByType" class="your.package.com.IngestorService" autowire="byType" />

<!-- autowiring by constructor is similar to type, but the DI will be done by constructor -->
<bean name="ingestorServiceConstructor" class="your.package.com.IngestorService" autowire="constructor" />

请包含您的完整 Spring 配置,以便更轻松地分析您的问题。

于 2015-06-23T09:59:39.020 回答
-1

当您使用基于注释的 DI 时,您不需要在 XML 中定义 bean。

@PostConstruct 可用于替换 xml 配置的 init 方法。

只需使用

    <context:component-scan base-package="..."/> <mvc:annotation-driven/>
于 2015-06-23T05:25:16.997 回答