Java Spring学习笔记----Bean的依赖注入
Posted zyfadmin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Spring学习笔记----Bean的依赖注入相关的知识,希望对你有一定的参考价值。
Spring常用的两种依赖注入方式:一种是设值注入方式,利用Bean的setter方法设置Bean的属性值;另一种是构造注入,通过给Bean的构造方法传递参数来实现Bean的属性赋值;
1、设值注入方式
直接上代码例子,示例的树结构图如下
Shape.java接口内容
package chapter3; public interface Shape { public double area();//求形状的面积 }
Circle.java内容:
package chapter3; public class Circle implements Shape { double r; public double getR(){ return this.r; } public void setR(double r){ this.r=r; } @Override public double area() { // TODO Auto-generated method stub return Math.PI*Math.pow(r, 2); } }
Rectangle.java内容
package chapter3; public class Rectangle implements Shape { double width,height; public double getWidth(){ return this.width; } public void setWidth(double width){ this.width=width; } public double getHeight(){ return this.height; } public void setHeight(double height){ this.height=height; } @Override public double area() { // TODO Auto-generated method stub return width*height; } }
AnyShape.java内容
package chapter3; public class AnyShape { Shape shape; public void setShape(Shape shape) {this.shape=shape;} public Shape getShape(){return this.shape;} public void outputArea(){ System.out.println("面积="+shape.area()); } }
Test.java内容
package chapter3; import org.springframework.context.ApplicationContext; import org.springframework.context.support.*; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new FileSystemXmlApplicationContext("src/myContext.xml"); AnyShape shape=(AnyShape)context.getBean("anyShape"); shape.outputArea(); AnyShape shape2=(AnyShape)context.getBean("anyShape2"); shape2.outputArea(); } }
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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="myShape" class="chapter3.Circle"> <property name="R"> <value>2.5</value> </property> </bean> <bean id="myShape2" class="chapter3.Rectangle"> <property name="height"> <value>2</value> </property> <property name="width"> <value>5</value> </property> </bean> <bean id="anyShape" class="chapter3.AnyShape"> <property name="shape"> <ref bean="myShape"/> </property> </bean> <bean id="anyShape2" class="chapter3.AnyShape"> <property name="shape"> <ref bean="myShape2"/> </property> </bean> </beans>
以上是关于Java Spring学习笔记----Bean的依赖注入的主要内容,如果未能解决你的问题,请参考以下文章
[原创]java WEB学习笔记98:Spring学习---Spring Bean配置及相关细节:如何在配置bean,Spring容器(BeanFactory,ApplicationContext),
Java框架spring Boot学习笔记:Bean的作用域
[原创]java WEB学习笔记97:Spring学习---Spring 中的 Bean 配置:IOC 和 DI