Spring——Bean配置

Spring配置方式:

1.XML文件配置

2.基于类名的文件配置

IOC容器的实现方式:

1.基于BeanFactory的实现

2.基于ApplicationContext的实现(ApplicationContext是BeanFactory的子接口,实现了更多的高级功能,属于高级层);

ApplicationContext主要使用以下三个实现类:

1.FileSystemXMLApplicationContext、ClassPathXMLApplicationContext和WebApplicationContext。ConfigurableApplicationContext是ApplicationContext的子接口,拓展了refresh()、close()方法,用于刷新和关闭上下文功能;

2.ApplicationContext的获取实例方法:getBean(#{id})和getBean(#{class}),后者当xml中id不一致但class的绝对路径不止一个时会抛出Bean类不独立的异常,所以不推荐;

依赖注入的方式:

1.属性注入;

  通过setter方法注入,使用<property>标签,name为指定Bean类中属性,使用value属性或<value>标签表明想要赋的值。

public class Beans {
    private String name;
    
    public Beans() {
        // TODO Auto-generated constructor stub
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public void hello() {
        System.out.println("hello:" + this.name);
    }
}

2.构造器注入;  构造方法注入:<construtor-arg>

	<bean id="car" class="com.mec.about_spring.core.Car">
		<constructor-arg value="Benchi" type="String"></constructor-arg>
		<constructor-arg value="shanghai" index="1"></constructor-arg>
		<constructor-arg value="300000" type="double"></constructor-arg>
	</bean>
	<bean id="car2" class="com.mec.about_spring.core.Car">
		<constructor-arg value="Baoma" type="String"></constructor-arg>
		<constructor-arg value="shanghai" index="1"></constructor-arg>
		<constructor-arg value="240" index="2" type="int"></constructor-arg>
	</bean>

其中当Bean中参数列表(参数类型、参数个数)发现混淆时,如300000,可被强转为double型,此时只使用作为下标标识的index属性已经不够用,需要type属性标明具体属性,以区别不同参数列表的构造器。

public class Car {
	private String brand;
	private String corp;
	private int maxSpeed;
	private double price;
	
	public Car(String brand, String corp, double price) {
		super();
		this.brand = brand;
		this.corp = corp;
		this.price = price;
	}

	public Car(String brand, String corp, int maxSpeed) {
		super();
		this.brand = brand;
		this.corp = corp;
		this.maxSpeed = maxSpeed;
	}

	public String toString() {
		return "Car [brand=" + brand + ", corp=" + corp + ", maxSpeed="
				+ maxSpeed + ", price=" + price + "]";
	}
	

}

 

输出为
hello:Spring
Car [brand=Benchi, corp=shanghai, maxSpeed=0, price=300000.0]
Car [brand=Baoma, corp=shanghai, maxSpeed=240, price=0.0]

3.工厂模式注入(很少使用);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值