简体   繁体   中英

Pass a constructor argument to a @component class in java

I am using spring with Java based configuration. I have a component class which needs to have its constructor auto-wired(rather at compile-time).

Here is the component class

package com.project.fileservices; 

@Component
public class FileU {

    FileWriter fw_output;

    @Autowired
    public FileU(String s){

    }
}

Configuration Class:

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

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

Here I need to auto-wire the FileU with Constructed String from Constructor

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

Answer from toongeorges will work, however there's a much simpler way by using @Value annotation . Since you have fileUnity in properties file, it's available to spring for autowiring by property name.

See the example below.

@Component
public class FileU {

    FileWriter fw_output;

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

    }
}

Try this:

@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){

    }
}

or if that does not work (I have not used the Qualifier annotation on a constructor yet):

@Component
public class FileU {

    FileWriter fw_output;

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

    public FileU(){

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM