相信一说到spring的自动注入作为Java程序员应该非常的熟悉,但是你对spring自动注入有没有深入的理解呢
首先所谓的自动注入也可以称之为自动装配,spring除了自动装配,还可以手动装配,下面通过Xml来看看一个手动装配的例子吧
package com.xp.service; public class HelloService { private ZullService zullService; public void query(){ System.out.println(zullService); } }
package com.xp.service; public class ZullService { }
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byType"> <bean id="helloService" class="com.xp.service.HelloService"> <property name="zullService"> <ref bean="zullService" /> </property> </bean> <bean id="zullService" class="com.xp.service.ZullService"> </bean> </beans>
上面的这个例子就是一个常见的手动装配的例子,但是在我们实际的开发过程中,很少会这么去用,因为比较繁琐,如果项目需要管理的Bean很多,这样一个一个的配置,很麻烦。Spring有两种主要的依赖注入的方式,官网上面有过说明,分为通过构造器注入,还有是通过set方式注入。那么对于现在Spirng开发主要用的是注解版的方式,我们在项目中是通过常用注解@Autowired的方式进行注入的,那么这种方式究竟是根据什么形式注入的呢,Spring装配模型有四种类,第一种 NO,第二种 ByType,第三中ByName ,第四种 构造器,那么@Autowired是如何注入的呢?看一下下一个例子
package com.xp.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class HelloService { @Autowired private ZullService zullService; public void setZullService(){ System.out.println("通过set方式注入"); } public void query(){ System.out.println(zullService); } }
package com.xp.service; import org.springframework.stereotype.Component; @Component public class ZullServ