上海网站建设公司兴田德润简介,网站建设新闻发布,南宁seo多少钱报价,公司展厅设计公司哪家好一点除了使用 XML 和 Annotation 的方式装配 Bean 以外#xff0c;还有一种常用的装配方式——自动装配。自动装配就是指 Spring 容器可以自动装配#xff08;autowire#xff09;相互协作的 Bean 之间的关联关系#xff0c;将一个 Bean 注入其他 Bean 的 Property 中。
要使用…除了使用 XML 和 Annotation 的方式装配 Bean 以外还有一种常用的装配方式——自动装配。自动装配就是指 Spring 容器可以自动装配autowire相互协作的 Bean 之间的关联关系将一个 Bean 注入其他 Bean 的 Property 中。
要使用自动装配就需要配置 元素的 autowire 属性。autowire 属性有五个值。
autowire 的属性和作用
名称说明byName根据 Property 的 name 自动装配如果一个 Bean 的 name 和另一个 Bean 中的 Property 的 name 相同则自动装配这个 Bean 到 Property 中。byType根据 Property 的数据类型Type自动装配如果一个 Bean 的数据类型兼容另一个 Bean 中 Property 的数据类型则自动装配。constructor根据构造方法的参数的数据类型进行 byType 模式的自动装配。autodetect如果发现默认的构造方法则用 constructor 模式否则用 byType 模式。no默认情况下不使用自动装配Bean 依赖必须通过 ref 元素定义。
示例自动装配。首先将 applicationContext.xml 配置文件修改成自动装配形式如下所示。
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xmlns:aophttp://www.springframework.org/schema/aopxmlns:phttp://www.springframework.org/schema/p xmlns:txhttp://www.springframework.org/schema/txxmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocation http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdbean idpersonDao classcom.mengma.annotation.PersonDaoImpl /bean idpersonService classcom.mengma.annotation.PersonServiceImplautowirebyName /bean idpersonAction classcom.mengma.annotation.PersonActionautowirebyName /
/beans在上述配置文件中用于配置 personService 和 personAction 的 元素中除了 id 和 class 属性以外还增加了 autowire 属性并将其属性值设置为 byName按属性名称自动装配。
默认情况下配置文件中需要通过 ref 装配 Bean但设置了 autowire“byName”Spring 会在配置文件中自动寻找与属性名字 personDao 相同的 找到后通过调用 setPersonDaoPersonDao personDao方法将 id 为 personDao 的 Bean 注入 id 为 personService 的 Bean 中这时就不需要通过 ref 装配了。
使用 JUnit 再次运行测试类中的 test() 方法控制台的显示结果如下图所示。 从输出结果中可以看出使用自动装配的方式同样完成了依赖注入。