怎么为Spring容器添加组件
更新:HHH   时间:2023-1-8


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

建个TestBean类

public class TestService {
}

新建一个beans.xml,写一个service的bean配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="testService" class="com.example.springboot.properties.service.TestService"></bean>
</beans>

然后可以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容器添加组件,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注天达云行业资讯频道。

返回编程语言教程...