Spring Boot希望@Component类成为@Configuration类中的@Bean

时间:2019-05-21 19:51:35

标签: java spring-boot components javabeans

当我测试自己的@Component类时,Spring boot告诉我应该在@Bean类中将该类声明为@Configuration

Field c in org.accountingSpringBoot.AccountingSpringBootApplication required a bean of type 'org.util.Cryptography' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'org.util.Cryptography' in your configuration.

代码:

主类:

@SpringBootApplication
public class AccountingSpringBootApplication implements CommandLineRunner {
    @Autowired
    ApplicationContext ctx;
    @Autowired
    Cryptography c;

    public static void main(String[] args) {
    SpringApplicationBuilder builder = new SpringApplicationBuilder(AccountingSpringBootApplication.class);
    builder.headless(false);

    ConfigurableApplicationContext context = builder.run(args);
    // SpringApplication.run(AccountingSpringBootApplication.class, args);

    }

    @Override
    public void run(String... args) throws Exception {

    System.out.println(c.decrypt(c.encrypt("password")));
    }
}

配置类:

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
    @Autowired
    private Environment env;

    @Bean
    @Scope(scopeName = "singleton")
    public SessionHandler sessionHandler() {
    return new SessionHandler();
    }

    @Bean
    @Scope(scopeName = "singleton")
    public SessionFactory sessionFactory() {
    SessionFactory sessionFactory;
    try {
        sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
    return sessionFactory;
    }

    @Bean
    public SecretKey secretKey() {
    String secretKey = env.getProperty("crypto.secretkey");
    byte[] decodedKey = Base64.getDecoder().decode(secretKey);
    SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length,
        env.getProperty("crypto.algorithm"));
    return originalKey;
    }
}

@Component类:

@Component
public class Cryptography {
    @Autowired
    private SecretKey secretKey;
    private Cipher cipher; // = Cipher.getInstance("AES");

    public Cryptography() {
    try {
        System.out.println("hhhhh");
        this.cipher = Cipher.getInstance("AES");
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

    public String encrypt(String plainText) throws Exception {
    byte[] plainTextByte = plainText.getBytes();
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] encryptedByte = cipher.doFinal(plainTextByte);
    Base64.Encoder encoder = Base64.getEncoder();
    String encryptedText = encoder.encodeToString(encryptedByte);
    return encryptedText;
    }

    public String decrypt(String encryptedText) throws Exception {
    Base64.Decoder decoder = Base64.getDecoder();
    byte[] encryptedTextByte = decoder.decode(encryptedText);
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
    String decryptedText = new String(decryptedByte);
    return decryptedText;
    }
}

3 个答案:

答案 0 :(得分:2)

您没有在代码中显示程序包声明,但是错误显示AccountingSpringBootApplication在程序包org.accountingSpringBoot中,而Cryptography在程序包org.util中。 / p>

@SpringBootApplication可以对带有注释的类的包和子包(即包org.accountingSpringBoot)进行组件扫描。

由于Cryptography位于软件包org.util中,因此不会对其进行扫描,因此@Component不会被Spring容器看到​​。

您可以:

  • Cryptography移动到org.accountingSpringBoot的子包中,例如org.accountingSpringBoot.util

  • AccountingSpringBootApplication移动到软件包org (不推荐)

  • 明确指定要扫描的软件包:

    @SpringBootApplication(scanBasePackages={"org.accountingSpringBoot", "org.util"})
    
  • 重新安排您的包装结构。
    我建议这样做,因为您当前使用的软件包太笼统,例如:

    org.janlan.accounting.AccountingApplication
    org.janlan.accounting.util.Cryptography
    

    janlan可以是您的公司名称,也可以是您的名称或类似名称。

您应该阅读有关Spring Boot应用程序的推荐软件包结构的文档:Locating the Main Application Class

答案 1 :(得分:1)

您没有使用默认的应用布局,因此未发现您的org.util.Cryptography类。

有一些可能的解决方案

  • 使用@ComponentScan
  • 使用默认的程序包布局。选中Locating the Main Application Class
  • 从Cryptography类中删除@Component(无论如何都找不到)。在您的一个配置类中声明一个用@Bean注释的方法,该方法返回加密实例。 (您的配置类对此方法使用了一些bean)

答案 2 :(得分:0)

您需要以某种方式将您的Configuration类告诉您的Cryptography类。 一种选择是将以下代码添加到您的AppConfig类中

@Bean
public Cryptography cryptography() {
    return new Cryptography()
}