组件扫描
运用组件扫描就不用添加bean标签,直接使用注解就可以将类的实例化控制交给spring容器。组件扫描也需要添加context命名空间,但是添加的标签不一样。我们只需要将注解添加到要实例化的类的前面,spring就会将该类添加到spring容器中。
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 可以激活@Autowired、@Resource @PostConstruct、@PreDestory注解-->
<!-- 可以激活更多注解,如@Component 、@controller、@service、@repository -->
<!-- 该标签隐式的包含了<context:annotation-config/> -->
<!--此标签用来扫描jee.pk2包中的所有类如果遇到@Component 、@controller、@service、@repository 这四个注解,就会创建bean,放入容器中-->
<context:component-scan base-package="jee.pk2"></context:component-scan>
</beans>
//@Component(value="")可以指定备案的name,如果不指定,默认使用类名作为那么
@Component
public class DBClientDaoImpl implements ClientDao{
public void insert() {
System.out.println("DBClientDao insert");
}
}
自动装配
自动装配就是bean标签添加一个outowire属性,这个属性有四个值分别是
<!-- autowire="byName"为这个bean的所有属性,寻找和属性名匹配的bean,然后注入依赖 -->
<!-- autowire="byType"为这个bean的所有属性,寻找和属性类型匹配的bean,然后注入依赖 -->
<!-- autowire="constructor" 为这个bean的构造器的所有参数,寻找和参数类型匹配的bean,然后注入依赖 -->
<bean id="clientService" class="jee.pk3.ClientService" autowire="byType"></bean>