Open ythy opened 5 years ago
Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class". A single @SpringBootApplication annotation can be used to enable those three features, that is:
@EnableAutoConfiguration
: enable Spring Boot’s auto-configuration mechanism@ComponentScan
: enable @Component scan on the package where the application is located@Configuration
: allow to register extra beans in the context or import additional configuration classes@EnableAutoConfiguration
annotation tells Spring Boot to "guess" how you will want to configure Spring, based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring will auto-configure an in-memory database.
@ComponentScan
tells Spring to look for other components, configurations, and services in the specified package. Spring is able to auto scan, detect and register your beans or components from pre-defined project package. If no package is specified current class package is taken as the root package.
此处警告
Field injection is not recommended
,修改为Setters injection正常。或者 constructor injection
Using @Autowired
@Autowired on Properties
The annotation can be used directly on properties, therefore eliminating the need for getters and setters:
@Autowired on Setters
he
@Autowired
annotation can be used on setter methods. In the below example, when the annotation is used on the setter method, the setter method is called with the instance of FooFormatter when FooService is created:@Autowired on Constructors
The
@Autowired
annotation can also be used on constructors. In the below example, when the annotation is used on a constructor, an instance of FooFormatter is injected as an argument to the constructor when FooService is created: