Wenaro
Wenaro

Reputation: 125

How to proper create bean Spring using annotations Bean and ComponentScan?

Main:

@SpringBootApplication
@ComponentScan(basePackageClasses = Application.class)
public class Application {

  public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
  }
}

Test class:

public class Test {

  @Bean
  public Test test(){
      return new Test();
  }
}

and when I'm trying to autowire it then i got this exception:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field test in TestWithAutowire required a bean of type 'Test' that could not be found.


Action:

Consider defining a bean of type 'rcms.backend.exception.Test' in your configuration.


Process finished with exit code 1

There is something hat I'm doing wrong, but I can't find it out.

Upvotes: 0

Views: 324

Answers (1)

Indra Basak
Indra Basak

Reputation: 7394

You can create a new configuration, let's say SpringConfiguration,

package my.pkg.config;

@Configuration
public class SpringConfiguration {
    @Bean
    public Test test(){
        return new Test();
    }
}

In your Application class, you can add the @ComponentScan annotation with the base packages where you would like Spring to scan for classes,

@SpringBootApplication
@ComponentScan(basePackageClasses = {"my.pkg.config", "my.pkg.example"})
public class Application {

  public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
  }
}

Now you can autowire Test in any Spring component. For example,

package my.pkg.example;

@Component
public class TestExample {

    @Autowired
    private Test tst;

}

Upvotes: 1

Related Questions