簡體   English   中英

如何在SpringBoot應用程序中自動裝配具有構造函數和參數的組件

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

我有一類具有自動裝配構造函數的類。

現在,當我在班級中自動裝配該類對象時。 我如何為構造函數傳遞參數?

示例代碼: 具有自動裝配構造函數的類:

@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?

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)定義一個文件,例如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;
}

使用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 /

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM