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

将构造函数参数传递给java中的@component类,java,spring,constructor,Java,Spring,Constructor,我正在使用基于Java配置的spring。我有一个组件类,它的构造函数需要自动连接(而不是在编译时) 下面是组件类 package com.project.fileservices; @Component public class FileU { FileWriter fw_output; @Autowired public FileU(String s){ } } 配置类: @Configuration @ComponentScan("com.pro

我正在使用基于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();
    }   
}
在这里,我需要使用构造函数中构造的字符串自动连接FileU

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

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

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

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

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


来自Toongerges的答案将起作用,但是有一种更简单的方法,使用。因为在属性文件中有
fileUnity
,所以spring可以按属性名进行自动关联

请参见下面的示例

@Component
public class FileU {

    FileWriter fw_output;

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

    }
}

有多种不同的方法,这取决于字符串值的实际来源。它是从属性文件等硬编码的。您的自动连接参数在大多数情况下不应该更改。您传递给它的字符串是否总是常量?实际上它来自属性文件。一旦它被传递,我不想在运行时更改它。不回答您的问题,但既然您有一个\@Configuration类,为什么不在其中使用\@Bean定义您的Bean并删除所有\@Autowired和\@Component注释?当您使用\@Autowired和\@组件注释时,您使代码依赖于Spring。如果使用\@Bean定义Bean,那么Spring配置与代码是分开的。让您的代码依赖于Spring是不够干净的。假设您创建了一个库,然后您强制库的用户使用相同的依赖项注入框架,而他们可能已经在使用另一个依赖项注入框架。
@Component
public class FileU {

    FileWriter fw_output;

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

    public FileU(){

    }
}
@Component
public class FileU {

    FileWriter fw_output;

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

    }
}