How to Autowire a Component which is having constructor with arguments in SpringBoot Application

邮差的信 提交于 2020-03-20 14:01:25

问题


I have a class having Autowired Constructor.

now when i am autowiring this class object in my class. how do i pass arguments for constructor??

example code: Class having Autowired Constructor:

@Component
public class Transformer {
    private String dataSource;
    @Autowired
    public Transformer(String dataSource)
    {
        this.dataSource = dataSource;
    }
}

Class using autowire for component having constructor with arguments:

@Component
    public class TransformerUser {
        private String dataSource;
        @Autowired
        public TransformerUser(String dataSource)
        {
            this.dataSource = dataSource;
        }
        @Autowired
        Transformer transformer;

    }

this code fails with message

"Unsatisfied dependency expressed through constructor parameter 0"

while creating bean of type Transformer.

how do i pass the arguments to Transformer while Autorwiring it??


回答1:


package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Transformer {
    private String datasource;

    @Autowired
    public Transformer(String datasource) {
        this.datasource=datasource;
        log.info(datasource);
    }
}

Then create a config file

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {
    @Bean
    public Transformer getTransformerBean() {
        return new Transformer("hello spring");
    }

    @Bean
    public String getStringBean() {
        return new String();
    }
}



回答2:


you can use resource files

1) define a file like database.properties and put a variable like

datasource=example

in this file

2) define a configuration class

@Configuration
@PropertySource(value = {"classpath:resources/database.properties"})
public class PKEServiceFactoryMethod {

   private final Environment environment;

   @Bean
   public String dataSource() {
      return environment.getProperty("dataSource");
   }
}

also you can use placeholder that is much better of using constructor in this case

@Component
@PropertySource(value = {"classpath:resources/database.properties"})
public class Transformer {
    @Value("${dataSource}")
    private String dataSource;
}



回答3:


Another solution using Spring annotations @Configuration and @Bean

AbstractEncryptor Abstract Class with parameters in the constructor

package com.jmendoza.springboot.crypto.v2.cipher;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public abstract class AbstractEncryptor {

    private byte[] key;
    private String algorithm;

    public AbstractEncryptor(String key, String algorithm) {
        this.key = key.getBytes(StandardCharsets.UTF_8);
        this.algorithm = algorithm;
    }

    public String encrypt(String plainText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return new String(Base64.getEncoder().encode(cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8))));
    }

    public String decrypt(String cipherText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)));
    }
}

CertificateEncryptor Class extends AbstractEncryptor

package com.jmendoza.springboot.crypto.v2.cipher;

public class CertificateEncryptor extends AbstractEncryptor {
    public CertificateEncryptor(String key, String algorithm) {
        super(key, algorithm);
    }
}

DestinyEncryptor Class extends AbstractEncryptor

package com.jmendoza.springboot.crypto.v2.cipher;

public class DestinyEncryptor extends AbstractEncryptor {
    public DestinyEncryptor(String key, String algorithm) {
        super(key, algorithm);
    }
}

ConfigEncryptor Class: Creating the beans passing parameters to the constructor

package com.jmendoza.springboot.crypto.v2.config;

import com.jmendoza.springboot.crypto.v2.cipher.CertificateEncryptor;
import com.jmendoza.springboot.crypto.v2.cipher.DestinyEncryptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ConfigEncryptor {

    @Value("${security.encryptor.key.certificate}")
    String keyCertificate;
    @Value("${security.encryptor.algorithm}")
    String algorithm;
    @Value("${security.encryptor.key.destiny}")
    String keyDestiny;

    @Bean
    public CertificateEncryptor certificateEncryptor() {
        return new CertificateEncryptor(keyCertificate, algorithm);
    }

    @Bean
    public DestinyEncryptor destinyEncryptor() {
        return new DestinyEncryptor(keyDestiny, algorithm);
    }
}

application.properties

server.port=8082
security.encryptor.algorithm=AES
security.encryptor.key.destiny=L2dvx46dfJMaiJA0
security.encryptor.key.certificate=M5mjd46dfSAaiLP4

Encryptor2Controller Class: Use the class CertificateEncryptor

package com.jmendoza.springboot.crypto.v2.controller;

import com.jmendoza.springboot.crypto.v2.cipher.CertificateEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v2/cipher")
public class Encryptor2Controller {

    @Autowired
    CertificateEncryptor certificateEncryptor;

    @GetMapping(value = "encrypt/{value}")
    public String encrypt(@PathVariable("value") final String value) throws Exception {
        return certificateEncryptor.encrypt(value);
    }

    @GetMapping(value = "decrypt/{value}")
    public String decrypt(@PathVariable("value") final String value) throws Exception {
        return certificateEncryptor.decrypt(value);
    }
}

Example

http://localhost:8082/v2/cipher/encrypt/jonathan

nrWRgt1CRb9AUYZQ6Ut0EA==

http://localhost:8082/v2/cipher/decrypt/nrWRgt1CRb9AUYZQ6Ut0EA==

jonathan

Github: https://github.com/JonathanM2ndoza/Spring-Boot-Crypto

View package /com/jmendoza/springboot/crypto/v2/



来源:https://stackoverflow.com/questions/50601188/how-to-autowire-a-component-which-is-having-constructor-with-arguments-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!