Josh M.
Josh M.

Reputation: 27811

Configure auto-wired service injection with "code"

I've posted a similar question, but I need to elaborate with an example to get a useful answer.

I am not sure, using Spring Boot, how to define a specific instance of a class which Spring should use to inject into @Autowired dependent fields/constructors.

Suppose I have a utility class which is in a library which I either a) don't have access to change, or b) do not want to add a dependency on Spring Boot to.

SecurityUtil -- takes in two string arguments which would likely come from some application-level config (defined in an external package).

public class SecurityUtil {
    private final String algorithm;
    private final String key;

    public SecurityUtil(String algorithm, String key) {
        // ...
    }
}

PasswordHelper -- uses SecurityUtil to sign a password (for example).

public class PasswordHelper {
    private final SecurityUtil securityUtil;

    @Autowired
    public PasswordHelper(SecurityUtil securityUtil) {
        // ...
    }
}

During application startup, I want to be able to create a singleton instance of SecurityUtil using the algorithm and key defined in my application's configuration (or elsewhere). I assumed that I would be able to add a class similar to the one below, but I'm not sure how to configure the injection of my singleton.

DIConfig -- configure things for DI (e.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DIConfig
{
    @Value("${security-util.key}")
    private String securityUtilKey;

    @Value("${security-util.algorithm}")
    private String securityUtilAlgorithm;

    public void configure(SpringDiMagicalConfig config)
    {
        // register a singleton SecurityUtil instance
        config.register(new SecurityUtil(securityUtilKey, securityUtilAlgorithm));
    }
}

How can I accomplish this configuration using Java / Spring Boot?

Upvotes: 0

Views: 84

Answers (2)

Patrick
Patrick

Reputation: 12744

You can go this way:

@Component
public class DiConfig {

    @Bean
    public SecurityUtil securityUtil(
            @Value("${security-util.key}") String securityUtilKey,
            @Value("${security-util.algorithm}") String securityUtilAlgorithm) {
        return new SecurityUtil(securityUtilKey, securityUtilAlgorithm);
    }
}

Upvotes: 1

jingx
jingx

Reputation: 4014

Replace the configure method with:

@Bean
public SecurityUtil securityUtil()
{
    return new SecurityUtil(securityUtilKey, securityUtilAlgorithm);
}

Upvotes: 2

Related Questions