springboot2.2.6.RELEASE chapter3
2020-04-03 本文已影响0人
淼哥1986
Spring Boot favors Java-based configuration. Although it is possible to use SpringApplication with
XML sources, we generally recommend that your primary source be a single @Configuration class.
Usually the class that defines the main method is a good candidate as the primary @Configuration.
example:
1. Configuration Classes ( 使用java类进行配置 )
package com.github;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestConfig {
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setConfig1("testBean config");
return testBean;
}
}
这个配置就等同于之前在xml里的配置
<beans>
<bean id="testBean" class="com.github.TestBean"/>
</beans>
2. Auto-configuration ( 自动配置 )
Spring Boot自动配置尝试根据您添加的jar依赖项自动配置Spring应用程序。例如,如果HSQLDB在您的类路径上,并且您没有手动配置任何数据库连接bean,那么Spring Boot将自动配置内存中的数据库。
3. Disabling Specific Auto-configuration Classes ( 取消自动配置 )
package com.github.examples;
import com.github.TestConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.RestController;
//@SpringBootApplication()
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@RestController
@Import({TestConfig.class})
@ServletComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}