spring boot允许用户编写一个配置类,来取代以前的application.xml容器。
配置类书写
package com.itrucheng.springboot.config;
import com.itrucheng.springboot.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration //这个注解就是说明这是一个配置类,用来取代以前的xml容器
public class MyAppConfig {
@Bean //<bean id="方法名" class="返回值"> </bean>
public HelloService helloService() {
System.out.println("已经将helloService配置到容器当中");
return new HelloService();
}
}
被配置类
package com.itrucheng.springboot.service;
//简单表示一下
public class HelloService {
}
测试
@SpringBootTest
class SpringBoot02ConfigApplicationTests {
@Autowired
private ApplicationContext ioc; //ioc容器
@Test
public void test01() {
boolean b = ioc.containsBean("helloService"); //看下容器中是否包含了这个组件
System.out.println(b);
}
结果:true