怎么为Spring容器添加组件-创新互联
本篇文章给大家分享的是有关怎么为Spring容器添加组件,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

建个TestBean类
public class TestService {
}新建一个beans.xml,写一个service的bean配置
然后可以Application类里直接引用,也可以加载Configuration配置类上面
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class SpringbootPropertiesConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootPropertiesConfigApplication.class, args);
}
}Junit测试类:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest
class SpringbootPropertiesConfigApplicationTests {
//装载ioc容器
@Autowired
ApplicationContext ioc;
@Test
void contextLoads() {
//测试这个bean是否已经加载到Spring容器
boolean flag = ioc.containsBean("testService");
System.out.println(flag);
}
}经过测试,返回的是true,ok,换Springboot注解的方式实现
新建一个PropertiesConfig配置类,注意:组件的id就是方法名
import com.example.springboot.properties.service.TestService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration //@Configuration注解实践上也是一个Component
public class PerpertiesConfig {
//通过@Bean注解将组件添加到Spring容器,组件的id就是方法名
@Bean
public TestService testService1(){
return new TestService();
}
}Junit测试继续:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest
class SpringbootPropertiesConfigApplicationTests {
@Autowired
ApplicationContext ioc;
@Test
void contextLoads() {
//传方法名testService1
boolean flag = ioc.containsBean("testService1");
System.out.println(flag);
}
}以上就是怎么为Spring容器添加组件,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联网站建设公司行业资讯频道。
另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章题目:怎么为Spring容器添加组件-创新互联
分享地址:http://www.jxjierui.cn/article/dpgcop.html


咨询
建站咨询
