java 配置是spring4.x和springboot推荐的配置方式。
配置类一般是通过@Configuration、@Bean和@ComponentScan来实现的。
- @Configuration声明当前类是一个配置类,相当于spring的一个xml文件;
- @Bean注解加在方法上,当前方法返回一个Bean。
- @ComponentScan(“com.changhf”)一般是用来扫描指定package下的@Controller、@Service等注解
开发原则:全局配置实用java配置(如数据库相关配置、MVC相关配置),业务Bean的配置实用注解配置(如@Controller)
@Configuration
public class DemoConfiguration {
@Bean
public String message() {
return "message configuration";
}
}
public class DemoConfigurationTest {
@Test
public void testGetMessageBean() throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DemoConfiguration.class);
assertEquals("message configuration", ctx.getBean("message"));
}
}