Springboot配置类

it2022-05-30  84

配置类 MyAppConfig 

import com.test.springboot.service.HelloService; import org.springframework.context.annotation.*; /** * @Configuration:注解告诉springboot当前类是一个配置类,是来替代之前的spring配置文件。 * 在配置文件中用<bean></bean>标签添加组件 */ @Configuration @ComponentScan(basePackages = {"com.test.springboot"}) public class MyAppConfig { //将方法的返回值添加到容器中,容器中这个组件默认的ID是方法名 @Bean("helloService") public HelloService helloService() { System.out.println("配置类@bean给容器中添加组件了"); return new HelloService(); } }

HelloService 类

public class HelloService { public void say(String name) { System.out.println("****helloservice***" + name); } }

测试类

import com.test.springboot.bean.Person; import com.test.springboot.service.HelloService; import config.MyAppConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.test.context.junit4.SpringRunner; /** * springboot单元测试 * 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能 */ @RunWith(SpringRunner.class) @SpringBootTest public class SpringBoot02ConfigApplicationTests { @Autowired Person person; @Autowired ApplicationContext ioc; @Test public void testHelloService() { System.out.println("****************************************"); ApplicationContext context = new AnnotationConfigApplicationContext(MyAppConfig.class); HelloService helloService = (HelloService) context.getBean("helloService"); System.out.println(helloService); boolean flag = context.containsBean("helloService"); System.out.println("bean是否存在:" + flag); helloService.say("小明"); } }

执行结果

2019-05-08 17:27:32.553 INFO 2588 --- [ main] c.t.s.SpringBoot02ConfigApplicationTests : No active profile set, falling back to default profiles: default 2019-05-08 17:27:34.786 INFO 2588 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2019-05-08 17:27:35.123 INFO 2588 --- [ main] c.t.s.SpringBoot02ConfigApplicationTests : Started SpringBoot02ConfigApplicationTests in 3.134 seconds (JVM running for 4.183) **************************************** 配置类@bean给容器中添加组件了 com.test.springboot.service.HelloService@6eaa21d8 bean是否存在:true ****helloservice***小明 2019-05-08 17:27:35.741 INFO 2588 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor' Process finished with exit code 0

注解描述:

@Configuration : 指明当前类是一个配置类来替代之前的Spring配置文件,Spring boot的配置类,相当于Spring的配置文件。 Spring,通过配置文件添加组件 Spring boot,通过配置类的方式添加组件

@ComponentScan :作用就是根据定义的扫描路径,把符合扫描规则的类装配到spring容器中

@Bean :将方法的返回值添加到容器中

转载于:https://www.cnblogs.com/tidetrace/p/10844913.html


最新回复(0)