上一次我介绍了如何使用纯注解开发来给ioc容器注入beanspring注解驱动开发笔记_rslly的博客-优快云博客
这次我要介绍的是如何打印ioc容器中所有的bean的名称,这对开发调试非常有帮助,并且通过纯注解形式启动包扫描,把@controller@service@component这些注解的bean加载进ioc容器。
首先是打印ioc容器中的所有的bean的名称。
public class main {
public static void main(String []args) {
//加载xml文件,获取容器中的对象
ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
Person person = (Person) ac.getBean("person");
System.out.println(person.getWeight());
//加载配置类,获取容器中的对象
AnnotationConfigApplicationContext ac2= new AnnotationConfigApplicationContext(config.class);
Person person1 =(Person) ac2.getBean("person");
System.out.println(person1.getWeight());
var s = ac2.getBeanDefinitionNames();
for (String s1:s){
System.out.println(s1);
}
}
}
我使用了类型推断,这是java10的特性,java8无法正常编译,这个大家自行搜索,这里不是重点。
打印出来了,除了spring容器自身的bean就是自己注入的bean。
我们还是像上次那样先用xml文件进行扫描。
我们先写一个test类,使用了@service注解。
package top.rslly;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
@Service
public class test {
}
比较简单,只需要加上一行配置就行。但是从springboot开始我们就致力于消除配置文件,因为大量的xml文件,可读性可想而知。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean name="person" class="top.rslly.Person">
<constructor-arg name ="weight" value="100"/>
<constructor-arg name = "leg" value="2"/>
</bean>
<context:component-scan base-package="top.rslly"/>
</beans>
那如何使用注解进行包扫描呢?
很简单,可以用@componentscan。
package top.rslly;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(value = "top.rslly")
public class config {
@Bean
Person person (){
return new Person(150,2);
}
}
结果如下图。
容器中顺利注入了test类。