Spring boot wants @Component class to be @Bean in @Configuration class


Lively :

When I test my @Componentclass, spring boot tells me that this class must be declared as @Beanin the @Configurationclass:

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

@Componentkind:

@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 the package declaration in your code, but the error shows, AccountingSpringBootApplicationin the package org.accountingSpringBoot, and Cryptographyin the package org.util.

@SpringBootApplicationThe package and sub-package components of the package are scanned in the classes that carry the annotations, i.e. the package org.accountingSpringBoot.

Since it Cryptographyis encapsulated org.util, it is not scanned, so it @Componentwill not be visible to the Spring container.

you can:

  • move Cryptographyto a subpackage org.accountingSpringBoot, e.g.org.accountingSpringBoot.util

  • Move AccountingSpringBootApplicationto package org (not recommended)

  • Explicitly specify the packages to scan:

    @SpringBootApplication(scanBasePackages={"org.accountingSpringBoot", "org.util"})
    
  • Rearrange your package structure.
    I recommend this because your current package is too general, like:

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

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

You should read the documentation on the recommended encapsulation structure for spring boot applications: Find the main application class

Related


Spring Boot - @Configuration class in Spring component is null

even: I have a problem with spring boot when using autowiring on a configuration class. I minimized the problem by creating a small spring boot project on github . I created the MyBean class, declared it as @Component, and tried to autowire the MyConf class de

Spring Boot - @Configuration class in Spring component is null

even: I have a problem with spring boot when using autowiring on a configuration class. I minimized the problem by creating a small spring boot project on github . I created the MyBean class, declared it as @Component, and tried to autowire the MyConf class de

Spring Boot - @Configuration class in Spring component is null

even: I have a problem with spring boot when using autowiring on a configuration class. I minimized the problem by creating a small spring boot project on github . I created the MyBean class, declared it as @Component, and tried to autowire the MyConf class de

spring boot: convert class to bean

Patty: New to spring boots. I have a class that is implementing an interface and I want to convert this class to a bean. Is there a way? Here is the class: public class UnitTestContextProvider implements MockDataProvider { @Override public MockResult[

spring boot: convert class to bean

Patty: New to spring boots. I have a class that is implementing an interface and I want to convert this class to a bean. Is there a way? Here is the class: public class UnitTestContextProvider implements MockDataProvider { @Override public MockResult[

spring boot: convert class to bean

Patty: New to spring boots. I have a class that is implementing an interface and I want to convert this class to a bean. Is there a way? Here is the class: public class UnitTestContextProvider implements MockDataProvider { @Override public MockResult[

Will declaring @configuration on a class make it a spring bean?

KnowledgeSeeker001: I have a Spring Boot project and I have a class declared with @configurationannotations . Would a class be declared @configurationto make it a Spring bean? So here is my code below @Configuration public class DateTimeFormatConfiguration ext

Will declaring @configuration on a class make it a spring bean?

KnowledgeSeeker001: I have a Spring Boot project and I have a class declared with @configurationannotations . Would a class be declared @configurationto make it a Spring bean? So here is my code below @Configuration public class DateTimeFormatConfiguration ext

Spring transaction configuration (bean vs inner class)

noise In an example of Spring in action, I found that the configuration of the TransactionManager is achieved through nested classes: @Configuration @ComponentScan public class JpaConfig { //EntityManagerFactory, JpaVendorAdapter, DataSource @Beans @Config

Spring boot Controller cannot find bean class

hawk533 I'm new to Spring and I'm trying to build a simple registry using Spring Boot and use jpa to store user information in a mysql database. Here is my error stack. ---------- . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \

Create class bean in Spring Boot application?

deep I'm trying to bootstrap a redundant entity manager directly from a Spring Boot application. But I can't create a bean of a class that contains the methods I need. I am referring to the article below. https://dzone.com/articles/accessing-the-entitymanager-