IOC创建对象和spring注入方式
IOC容器的一些产品
Sun ONE技术体系下的IOC容器有:轻量级的有Spring、Guice、Pico Container、Avalon、HiveMind;重量级的有EJB;不轻不重的有JBoss,Jdon等等。Spring框架作为Java开发中SSH(Struts、Spring、Hibernate)三剑客之一,大中小项目中都有使用,非常成熟,应用广泛,EJB在关键性的工业级项目中也被使用,比如某些电信业务。
.Net技术体系下的IOC容器有:Spring.Net、Castle等等。Spring.Net是从Java的Spring移植过来的IOC容器,Castle的IOC容器就是Windsor部分。它们均是轻量级的框架,比较成熟,其中Spring.Net已经被逐渐应用于各种项目中。
所有的test文件:
以下是一个bean进行注入
流程:
Student类--->beans.xml--->test
这是调用的具体流程
Bean.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
" >https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
其中的一个Student类:
public class Student {
private String name;
private Address addr;
private String[] books;
private List<String> hobbies;
private Map<String, String> cards;
private Set<String> games;
private String wife;
private Properties info;
######省略了他们的set和get方法#########
public void show(){
System.out.println("name="+name+" addr="+addr.getAddress()+" books="+books);
System.out.println("books=");
for (int i = 0; i < books.length; i++) {
System.out.print(books[i]+""); }
System.out.println();
System.out.println("h+"+hobbies);
System.out.println("book="+books);
System.out.println("card="+cards);
System.out.println("gams="+games);
System.out.println("wife="+wife);
System.out.println("info="+info);
}}
所有的test文件:
附加:
Bean自动装配:
Scope指bean的作用域,在配置bean时,有scope属性来配置bean的作用域
注意:在整合Struts2和spring时,需要将action设为scope=”prototype”
autowire自动装配,简化spring配置, autowire=”方式名”
ByName根据名称(set方法名来的)去查找相应bean,如果有则装配上
Bytype 根据类型自动装配,不用管bean的id,但是同类型的bean只能有一个,建议慎用。
Constructor 当通过构造器注入实例化bean时适用bytype的方式装配构造方法
Bean.xml:
#改变之后:(byname方式)
#改可以整体自动装配的改变:bean后面的就可以省略,(bytype方式)
#改时(constructor方式)
修改dao里面的内容,需要把set给去掉,使用构造器凡是方法。
Dao和dao.impl:
service和Service.Impl:
test:
浙公网安备 33010602011771号