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

标签 java spring-boot components javabeans

当我测试我的 @Component 类时,Spring boot 告诉我这个类应该在 @Configuration 类中声明为 @Bean :

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

最佳答案

您没有在代码中显示包声明,但错误显示 AccountingSpringBootApplication 在包 org.accountingSpringBoot 中,并且 Cryptography 位于 org.util 包中。

@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

关于java - Spring Boot 希望@Component 类成为@Configuration 类中的@Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56245476/

相关文章:

java - Stripes ActionBean 事件总是解析为默认事件

spring-boot - 使用 Spring Websocket 向特定用户发送消息

angular - 如何在 Angular 中引用和使用另一个模块中的组件?

unit-testing - 测试 Angular 2 中 "(window:resize)"事件触发的函数

javafx声音/视频播放

java - 实现 "Invite Friends"功能?

java - 如何设置不是模拟bean的bean的字段

mysql - Hibernate 在为 mysql 生成 ddl 时添加唯一约束

delphi - 可以将组件及其事件处理程序复制到新窗体或框架的 Delphi 6 实用程序或 IDE 专家?

java - 如何禁用 jackson 的字符转义