如何在SpringBoot应用程序中自动装配具有参数的构造函数的Component

时间:2018-05-30 09:32:19

标签: java spring-boot constructor arguments autowired

我有一个有Autowired Constructor的课程。

现在,当我在班上自动装配这个类对象时。我如何传递构造函数的参数?

示例代码: 具有Autowired Constructor的类:

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

使用带有参数的构造函数的组件使用autowire的类:

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

    }

此代码失败并显示消息

  

“通过构造函数参数0表示的不满意的依赖”

     

创建Transformer类型的bean。

如何在自动布线时将参数传递给Transformer?

3 个答案:

答案 0 :(得分:3)

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);
    }
}

然后创建配置文件

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();
    }
}

答案 1 :(得分:0)

您可以使用资源文件

1)定义一个像database.properties这样的文件并输入一个像

这样的变量
  

数据源=示例

在此文件中

2)定义配置类

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

   private final Environment environment;

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

你也可以使用占位符,在这种情况下使用构造函数更好

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

答案 2 :(得分:0)

使用Spring注释@Configuration和@Bean的另一种解决方案

AbstractEncryptor抽象类,其构造函数中带有参数

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类扩展了AbstractEncryptor

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

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

DestinyEncryptor类扩展了AbstractEncryptor

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

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

ConfigEncryptor类:创建将参数传递给构造函数的bean

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类:使用类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);
    }
}

示例

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

nrWRgt1CRb9AUYZQ6Ut0EA ==

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

乔纳森

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

查看软件包/ com / jmendoza / springboot / crypto / v2 /