Spring Boot wants @Component class to be a @Bean in @Configuration class

janlan :

When I am testing my @Component class, Spring boot tells me that this class should be declared as @Bean in @Configuration class:

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.

Code:

Main class:

@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 class:

@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 class:

@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;
    }
}
Andreas :

You don't show package declarations in your code, but the error shows that AccountingSpringBootApplication is in package org.accountingSpringBoot, and that Cryptography is in package org.util.

The @SpringBootApplication enables component scanning of the package and sub-packages of the class carrying the annotation, i.e. of package org.accountingSpringBoot.

Since Cryptography is in package org.util, it is not scanned, so the @Component is not seen by the Spring container.

You can:

  • Move Cryptography to a sub-package of org.accountingSpringBoot, e.g. org.accountingSpringBoot.util

  • Move AccountingSpringBootApplication to package org (not recommended)

  • Explicitly specify which packages to scan:

    @SpringBootApplication(scanBasePackages={"org.accountingSpringBoot", "org.util"})
    
  • Re-arrange your package structure.
    I recommend this, since you current packages are too generic, e.g.:

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

    Where janlan could be your company name, or your name, or something like that.

You should read the documentation about the recommended package structure of a Spring Boot application: Locating the Main Application Class

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=78899&siteId=1