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.工厂模式注入(很少使用);