简体   繁体   中英

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.

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM