@ImportResource(不方便)
导入配置文件,让配置文件生效
用法:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
但是这种方法需要单个单个注入配置文件,相当的麻烦,Spring Boot中推荐添加组件的方式:全注解方式
- 首先我们来写一个配置类========Spring配置文件
- 使用@Bean给容器中添加组件
package com.example.demo.config;
import com.example.demo.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*
* 指明当前类是配置类,替代之前的Spring配置文件
* 在之前的配置文件中<bean></bean>标签来添加组件,而在配置类中用@Bean注解
* */
@Configuration
public class Myconfig {
//将方法的返回值添加到容器中,容器中组件默认的id就是方法名
@Bean
public HelloService helloService(){
return new HelloService();
}
}
测试一下
//注意ApplicationContext不要导错包
@Autowired
ApplicationContext ioc;
@Test
void testHelloWord(){
boolean n=ioc.containsBean("helloService");
System.out.println(n);
}
结果: