Как автоматически связать компонент, имеющий конструктор с аргументами в приложении SpringBoot - PullRequest
0 голосов
/ 30 мая 2018

У меня есть класс, имеющий конструктор Autowired.

теперь, когда я автоматически подключаю этот объект класса в своем классе.как передать аргументы для конструктора ??

пример кода: Класс, имеющий конструктор Autowired:

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

как передать аргументы в Transformer при автозаписи ??

Ответы [ 3 ]

0 голосов
/ 30 мая 2018
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();
    }
}
0 голосов
/ 24 августа 2019

Другое решение, использующее аннотации Spring @Configuration и @ Bean

AbstractEncryptor Abstract Class с параметрами в конструкторе

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 /

0 голосов
/ 30 мая 2018

вы можете использовать файлы ресурсов

1) определить файл, такой как database.properties, и поместить переменную, например,

datasource = пример

вэтот файл

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