将构造函数参数传递给java中的@component类

时间:2017-08-09 21:53:24

标签: java spring constructor

我使用带有基于Java的配置的spring。我有一个组件类,需要将其构造函数自动连接(而不是在编译时)。

这是组件类

package com.project.fileservices; 

@Component
public class FileU {

    FileWriter fw_output;

    @Autowired
    public FileU(String s){

    }
}

配置类:

@Configuration
@ComponentScan("com.project")
public class ResponseConfig {

@Bean
    public  ResponseTypeService protectionResponse() throws Exception{
        return new ProtectionTypeResponse();
    }   
}

这里我需要使用Constructor中的Constructed String自动连接FileU

 class ProtectionTypeResponse{
      @Autowired
      FileU filewriter; // i want the constructed(with constructor) FileU object.
    }

3 个答案:

答案 0 :(得分:0)

来自toongeorges的回答会起作用,但使用@Value annotation会有更简单的方法。由于您在属性文件中有fileUnity,因此可以按属性名称弹出以进行自动装配。

请参阅下面的示例。

@Component
public class FileU {

    FileWriter fw_output;

    public FileU(@Value("${fileUnit}") String s){

    }
}

答案 1 :(得分:-1)

试试这个:

@Configuration
@ComponentScan("com.project")
public class ResponseConfig {

    @Bean
    public ResponseTypeService protectionResponse() throws Exception{
        return new ProtectionTypeResponse();
    }

    @Bean
    @Qualifier("fileUInit")
    public String fileUInit() {
        return "whatever";
    }
}


@Component
public class FileU {

    FileWriter fw_output;

    @Autowired
    public FileU(@Qualifier("fileUInit") String s){

    }
}

或者如果这不起作用(我还没有在构造函数上使用限定符注释):

@Component
public class FileU {

    FileWriter fw_output;

    @Autowired
    @Qualifier("fileUInit")
    private String s;

    public FileU(){

    }
}

答案 2 :(得分:-3)

以下是@Autowired构造函数注入的代码片段

@Autowired  
public void ProtectionTypeResponse(FileU fileu) {   
         //...
    }