当前位置: 移动技术网 > IT编程>开发语言>Java > 浅谈spring ioc的注入方式及注入不同的数据类型

浅谈spring ioc的注入方式及注入不同的数据类型

2019年07月19日  | 移动技术网IT编程  | 我要评论

关于spring-ioc的简单使用参考:

1、通过set方法注入不同数据类型

测试类代码(set方式注入的属性一定要加set方法)

/**通过set方法注入示例*/
public class ioc_by_set {
	/**注入integer类型参数*/
	private integer id;
	/**注入string类型参数*/
	private string name;
	/**注入实体bean*/
	private user user;
	/**注入数组*/
	private object[] array;
	/**注入list集合*/
	private list<object> list;
	/**注入set集合*/
	private set<object> set;
	/**注入map键值对*/
	private map<object, object> map;
	/**注入properties类型*/
	private properties properties;
	/**注入空字符串*/
	private string emptyvalue;
	/**注入null值*/
	private string nullvalue = "";
	/**检测注入的属性是否全部正确*/
	public boolean checkattr() {
		if(id == null) {
			return false;
		} else {
			system.out.println("id:" + id);
		}
		system.out.println("--------------------------");
		if(name == null) {
			return false;
		} else {
			system.out.println("name:" + name);
		}
		system.out.println("--------------------------");
		if(user == null) {
			return false;
		} else {
			system.out.println("bean:" + user.getid() + "|" + 
			          user.getusername() + "|" + user.getpassword());
		}
		system.out.println("--------------------------");
		if(array == null) {
			return false;
		} else {
			system.out.println("array:");
			for (object object : array) {
				system.out.println(object.tostring());
			}
		}
		system.out.println("--------------------------");
		if(list == null) {
			return false;
		} else {
			system.out.println("list:");
			for (object object : list) {
				system.out.println(object.tostring());
			}
		}
		system.out.println("--------------------------");
		if(set == null) {
			return false;
		} else {
			system.out.println("set:");
			for (object object : set) {
				system.out.println(object.tostring());
			}
		}
		system.out.println("--------------------------");
		if(map == null) {
			return false;
		} else {
			set<entry<object, object>> set = map.entryset();
			system.out.println("map:");
			for (entry<object, object> entry : set) {
				system.out.println(entry.getkey() + "|" + entry.getvalue());
			}
		}
		system.out.println("--------------------------");
		if(properties == null) {
			return false;
		} else {
			set<entry<object, object>> set = properties.entryset();
			system.out.println("properties:");
			for (entry<object, object> entry : set) {
				system.out.println(entry.getkey() + "|" + entry.getvalue());
			}
		}
		system.out.println("--------------------------");
		if(!"".equals(emptyvalue))
		      return false;
		system.out.println("--------------------------");
		if(!(null == nullvalue))
		      return false;
		system.out.println("--------------------------");
		system.out.println("全部正确!!!");
		return true;
	}
	public void setid(integer id) {
		this.id = id;
	}
	public void setname(string name) {
		this.name = name;
	}
	public void setuser(user user) {
		this.user = user;
	}
	public void setarray(object[] array) {
		this.array = array;
	}
	public void setlist(list<object> list) {
		this.list = list;
	}
	public void setset(set<object> set) {
		this.set = set;
	}
	public void setmap(map<object, object> map) {
		this.map = map;
	}
	public void setproperties(properties properties) {
		this.properties = properties;
	}
	public void setemptyvalue(string emptyvalue) {
		this.emptyvalue = emptyvalue;
	}
	public void setnullvalue(string nullvalue) {
		this.nullvalue = nullvalue;
	}
}

applicationcontext.xml配置

  <!-- set方式注入 -->
  <bean id="ioc_by_set" class="com.bc.ioc.demo01.ioc_by_set">
    <!-- 注入id属性 -->
    <property name="id" value="1"/>
    <!-- 使用<![cdata[]]>标记处理xml特 殊字符 -->
    <property name="name">
      <!-- 也可以使用p&g -->
      <value><![cdata[p&g]]></value>
    </property>
    <!-- 定义内部bean注入 -->
    <property name="user">
      <bean class="com.bc.pojo.user">
        <property name="id" value="1"/>
        <property name="username" value="内部bean"/>
        <property name="password" value="233"/>
      </bean>
    </property>
    <!-- 注入数组类型 -->
    <property name="array">
      <array>
        <!-- 定义数组元素 -->
        <value>array01</value>
        <value>array02</value>
        <value>array03</value>
      </array>
    </property>
    <!-- 注入list类型 -->
    <property name="list">
      <list>
        <!-- 定义list中元素 -->
        <value>list01</value>
        <value>list02</value>
        <value>list03</value>
      </list>
    </property>
    <!-- 注入set类型 -->
    <property name="set">
      <set>
        <!-- 定义set中元素 -->
        <value>set01</value>
        <value>set02</value>
        <value>set03</value>
      </set>
    </property>
    <!-- 注入map类型 -->
    <property name="map">
      <map>
        <!-- 定义map中的键值对 -->
        <entry>
          <key>
            <value>mapkey01</value>
          </key>
          <value>mapvalue01</value>
        </entry>
        <entry>
          <key>
            <value>mapkey02</value>
          </key>
          <value>mapvalue02</value>
        </entry>
      </map>
    </property>
    <!-- 注入properties类型 -->
    <property name="properties">
      <props>
        <!-- 定义properties中的键值对 -->
        <prop key="propkey1">propvalue1</prop>
        <prop key="propkey2">propvalue2</prop>
      </props>
    </property>
    <!-- 注入空字符串 -->
    <property name="emptyvalue">
      <value></value>
    </property>
    <!-- 注入null值 -->
    <property name="nullvalue">
      <null/>
    </property>
  </bean>

测试代码

public class ioc_test {
	private applicationcontext ctx;
	@before
	  public void load() {
		//读取applicationcontext.xml配置文件
		ctx = new classpathxmlapplicationcontext("applicationcontext.xml");
	}
	@test
	  public void settest() {
		ioc_by_set ioc = (ioc_by_set) ctx.getbean("ioc_by_set");
		ioc.checkattr();
	}
}

控制台结果:

id:1
--------------------------
name:p&g
--------------------------
bean:1|内部bean|233
--------------------------
array:
array01
array02
array03
--------------------------
list:
list01
list02
list03
--------------------------
set:
set01
set02
set03
--------------------------
map:
mapkey01|mapvalue01
mapkey02|mapvalue02
--------------------------
properties:
propkey2|propvalue2
propkey1|propvalue1
--------------------------
--------------------------
--------------------------
全部正确!!!

2、通过构造方法注入各种类型属性

注意:使用jdk1.8版本请将spring相关jar包升级到4.x版本以上,否则不兼容构造方法注入

测试类代码

/** 通过构造方法注入示例 */
public class ioc_by_constructor {
	private integer id;
	private string name;
	private user user;
	private list<object> list;
	public ioc_by_constructor() {
	}
	public ioc_by_constructor(integer id, string name, user user,
	      list<object> list) {
		this.id = id;
		this.name = name;
		this.user = user;
		this.list = list;
	}
	/**检查是否注入成功*/
	public boolean checkattr() {
		if(id == null) {
			return false;
		} else {
			system.out.println("id:" + id);
		}
		system.out.println("----------------------------");
		if(name == null) {
			return false;
		} else {
			system.out.println("name:" + name);
		}
		system.out.println("----------------------------");
		if(user == null) {
			return false;
		} else {
			system.out.println("user:" + user.getid() + "|" + 
			          user.getusername() + "|" + user.getpassword());
		}
		system.out.println("----------------------------");
		if(list == null) {
			return false;
		} else {
			system.out.println("list:");
			for (object object : list) {
				system.out.println(object.tostring());
			}
		}
		system.out.println("----------------------------");
		system.out.println("全部正确!!!");
		return true;
	}
}

applicationcontext.xml配置

  <!-- 构造方法注入 演示几种类型-->
  <bean id="ioc_by_constructor" class="com.bc.ioc.demo02.ioc_by_constructor">
    <!-- 注入integer属性,可以选择使用index指定参数位置,也可以选择使用type指定参数类型 -->
    <constructor-arg index="0" value="1" type="java.lang.integer"/>
    <!-- 注入字符串 -->
    <constructor-arg value="p&g"/>
    <!-- 注入对象 -->
    <constructor-arg>
      <!-- 内建对象 -->
      <bean class="com.bc.pojo.user">
        <constructor-arg value="1"/>
        <constructor-arg value="构造内部bean"/>
        <constructor-arg value="666"/>
      </bean>
    </constructor-arg>
    <!-- 注入集合 -->
    <constructor-arg>
      <list>
        <value>list01</value>
        <value>list02</value>
        <value>list03</value>
      </list>
    </constructor-arg>
  </bean>

测试代码:

public class ioc_test {
	private applicationcontext ctx;
	@before
	  public void load() {
		//读取applicationcontext.xml配置文件
		ctx = new classpathxmlapplicationcontext("applicationcontext.xml");
	}
	@test
	  public void constructortest() {
		ioc_by_constructor ioc = (ioc_by_constructor) ctx.getbean("ioc_by_constructor");
		ioc.checkattr();
	}
}

控制台结果:

id:1
----------------------------
name:p&g
----------------------------
user:1|构造内部bean|666
----------------------------
list:
list01
list02
list03
----------------------------
全部正确!!!

3、自动注入(自动装配)

自动装配虽然能节省一些代码但是不推荐使用

测试类代码:

/**自动装配注入*/
public class ioc_by_auto {
	private user user;
	/**检查是否注入成功*/
	public boolean checkattr() {
		if(user == null) {
			return false;
		} else {
			system.out.println("user:" + user.getid() + "|" + 
			          user.getusername() + "|" + user.getpassword());
		}
		system.out.println("正确!!!");
		return true;
	}
	/**自动装配的属性需要设置set方法*/
	public void setuser(user user) {
		this.user = user;
	}
}

applicationcontext.xml配置

  <!-- 被自动装配获取的bean -->
  <bean id="user" class="com.bc.pojo.user">
    <property name="id" value="1"/>
    <property name="username" value="自动装配"/>
    <property name="password" value="233"/>
  </bean>
  <!-- 自动装配的bean
     autowire:byname 根据类的属性名查找与之命名相同的id的bean进行装配
         bytype 根据类的属性类型查找唯一一个匹配类型的bean,如果有多个bean匹配则抛出异常
         constructor 根据类的构造方法参数类型匹配对应的bean
         no 默认,表示不使用自动装配
         default:由上级标签<beans>的default-autowire属性确定 -->
  <bean id="ioc_by_auto" class="com.bc.ioc.demo03.ioc_by_auto" autowire="byname"></bean>

测试代码

public class ioc_test {
	private applicationcontext ctx;
	@before
	  public void load() {
		//读取applicationcontext.xml配置文件
		ctx = new classpathxmlapplicationcontext("applicationcontext.xml");
	}
	@test
	  public void autotest() {
		ioc_by_auto ioc = (ioc_by_auto) ctx.getbean("ioc_by_auto");
		ioc.checkattr();
	}
}

控制台结果

user:1|自动装配|233
正确!!!

以上使用的是byname模式,其他模式配置代码已经注明,不做测试。

4、使用p命名空间注入属性

测试类代码

/**使用p命名空间注入*/
public class ioc_by_p {
	private integer id;
	private string name;
	private user user;
	/**检查是否注入成功*/
	public boolean checkattr() {
		if(id == null) {
			return false;
		} else {
			system.out.println("id:" + id);
		}
		system.out.println("----------------------------");
		if(name == null) {
			return false;
		} else {
			system.out.println("name:" + name);
		}
		system.out.println("----------------------------");
		if(user == null) {
			return false;
		} else {
			system.out.println("user:" + user.getid() + "|" + 
			          user.getusername() + "|" + user.getpassword());
		}
		system.out.println("----------------------------");
		system.out.println("全部正确!!!");
		return true;
	}
	//使用p命名空间注入属性需要设置set方法
	public void setid(integer id) {
		this.id = id;
	}
	public void setname(string name) {
		this.name = name;
	}
	public void setuser(user user) {
		this.user = user;
	}
}

applicationcontext.xml配置

  <!-- 使用p命名空间注入各种类型属性 -->
  <bean id="user2" class="com.bc.pojo.user">
    <property name="id" value="1"/>
    <property name="username" value="p"/>
    <property name="password" value="233"/>
  </bean>
  <bean id="ioc_by_p" class="com.bc.ioc.demo04.ioc_by_p" p:id="1" 
    p:name="命名空间" p:user-ref="user2"></bean>

测试代码

public class ioc_test {
	private applicationcontext ctx;
	@before
	  public void load() {
		//读取applicationcontext.xml配置文件
		ctx = new classpathxmlapplicationcontext("applicationcontext.xml");
	}
	@test
	  public void ptest() {
		ioc_by_p ioc = (ioc_by_p) ctx.getbean("ioc_by_p");
		ioc.checkattr();
	}
}

控制台结果

id:1
----------------------------
name:命名空间
----------------------------
user:1|p|233
----------------------------
全部正确!!!

5、使用注解方式注入

spring在3.0以后,提供了基于annotation(注解)的注入。

1.@autowired-对成员变量、方法和构造函数进行标注,来完成自动装配的工作,不推荐使用

2.@qualifier-配合@autowired来解决装配多个同类型的bean

3.@resource-jsr-250标准注解,作用相当于@autowired,只不过@autowired按bytype自动注入,而@resource默认按byname自动注入

4.@postconstruct-在方法上加上注解@postconstruct,这个方法就会在bean初始化之后被spring容器执行

5.@predestroy-在方法上加上注解@predestroy,这个方法就会在bean初始化之后被spring容器执行

6.@component-只需要在对应的类上加上一个@component注解,就将该类定义为一个bean,不推荐使用,推荐使用更加细化的三种:@repository、@service、@controller

@repository存储层bean

@service业务层bean

@controller展示层bean

7.@scope-定义bean的作用范围

首先配置applicationcontext.xml开启注解

  <!-- 扫描包中注解标注的类 -->
  <context:component-scan base-package="com.bc.ioc.demo05"/>

实体bean加注解

@repository
public class user {
	private integer id = 1;
	private string username = "注解注入";
	private string password = "233";
	public user() {
		super();
	}
	public user(integer id, string username, string password) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
	}
	public integer getid() {
		return id;
	}
	public string getusername() {
		return username;
	}
	public string getpassword() {
		return password;
	}
	public void setid(integer id) {
		this.id = id;
	}
	public void setusername(string username) {
		this.username = username;
	}
	public void setpassword(string password) {
		this.password = password;
	}
}

测试类代码加注解

/**使用注解注入属性*/
@service("ioc_by_annotation")
public class ioc_by_annotation {
	@resource
	  private user user;
	public void setuser(user user) {
		this.user = user;
	}
	/**检查是否注入成功*/
	public boolean checkattr() {
		if(user == null) {
			return false;
		} else {
			system.out.println("user:" + user.getid() + "|" + 
			          user.getusername() + "|" + user.getpassword());
		}
		system.out.println("正确!!!");
		return true;
	}
}

测试代码

public class ioc_test {
	private applicationcontext ctx;
	@before
	  public void load() {
		//读取applicationcontext.xml配置文件
		ctx = new classpathxmlapplicationcontext("applicationcontext.xml");
	}
	@test
	  public void annotationtest() {
		ioc_by_annotation ioc = (ioc_by_annotation) ctx.getbean("ioc_by_annotation");
		ioc.checkattr();
	}
}

控制台输出

经测试使用注解注入如果applicationcontext.xml配置有其他注入方式会报错,也会导致其他注入方式异常。

user:1|注解注入|233
正确!!!

6、通过配置静态工厂方法bean注入

静态工厂代码

/**静态工厂*/
public class staticfactory {
	public static integer getid() {
		return 1;
	}
	public static string getname() {
		return "静态工厂";
	}
	public static user getuser() {
		return new user(1, "工厂user", "666");
	}
}

测试类代码

/** 通过静态工厂方式注入 */
public class ioc_by_staticfactory {
	private integer id;
	private string name;
	private user user;
	/** 检查是否注入成功 */
	public boolean checkattr() {
		if (id == null) {
			return false;
		} else {
			system.out.println("id:" + id);
		}
		system.out.println("----------------------------");
		if (name == null) {
			return false;
		} else {
			system.out.println("name:" + name);
		}
		system.out.println("----------------------------");
		if (user == null) {
			return false;
		} else {
			system.out.println("user:" + user.getid() + "|"
			          + user.getusername() + "|" + user.getpassword());
		}
		system.out.println("----------------------------");
		system.out.println("全部正确!!!");
		return true;
	}
	/**需要为需要注入的属性设置set方法*/
	public void setid(integer id) {
		this.id = id;
	}
	public void setname(string name) {
		this.name = name;
	}
	public void setuser(user user) {
		this.user = user;
	}
}

applicationcontext.xml配置

  <!-- 配置静态工厂方法bean 其实就是将工厂方法返回的数值配置成bean -->
  <bean id="factory_id" class="com.bc.ioc.demo06.staticfactory" factory-method="getid"/>
  <bean id="factory_name" class="com.bc.ioc.demo06.staticfactory" factory-method="getname"/>
  <bean id="factory_user" class="com.bc.ioc.demo06.staticfactory" factory-method="getuser"/>
  <!-- 注入对应的静态工厂方法bean -->
  <bean id="ioc_by_staticfactory" class="com.bc.ioc.demo06.ioc_by_staticfactory">
    <property name="id" ref="factory_id"/>
    <property name="name" ref="factory_name"/>
    <property name="user" ref="factory_user"/>
  </bean>

测试代码

public class ioc_test {
	private applicationcontext ctx;
	@before
	  public void load() {
		//读取applicationcontext.xml配置文件
		ctx = new classpathxmlapplicationcontext("applicationcontext.xml");
	}
	@test
	  public void staticfactorytest() {
		ioc_by_staticfactory ioc = (ioc_by_staticfactory) ctx.getbean("ioc_by_staticfactory");
		ioc.checkattr();
	}
}

控制台输出结果

id:1
----------------------------
name:静态工厂
----------------------------
user:1|工厂user|666
----------------------------
全部正确!!!

7、通过实例工厂方法注入

与静态工厂区别在于实例工厂不是静态的,需要先new 一个实例工厂对象,才可以配置其方法,而new 的这个对象也由spring来管理

工厂代码

/**实例工厂*/
public class factory {
	public integer getid() {
		return 1;
	}
	public string getname() {
		return "实例工厂";
	}
	public user getuser() {
		return new user(1, "实例工厂user", "233");
	}
}

测试类代码

/**实例工厂注入*/
public class ioc_by_factory {
	private integer id;
	private string name;
	private user user;
	/** 检查是否注入成功 */
	public boolean checkattr() {
		if (id == null) {
			return false;
		} else {
			system.out.println("id:" + id);
		}
		system.out.println("----------------------------");
		if (name == null) {
			return false;
		} else {
			system.out.println("name:" + name);
		}
		system.out.println("----------------------------");
		if (user == null) {
			return false;
		} else {
			system.out.println("user:" + user.getid() + "|"
			          + user.getusername() + "|" + user.getpassword());
		}
		system.out.println("----------------------------");
		system.out.println("全部正确!!!");
		return true;
	}
	/**需要为需要注入的属性设置set方法*/
	public void setid(integer id) {
		this.id = id;
	}
	public void setname(string name) {
		this.name = name;
	}
	public void setuser(user user) {
		this.user = user;
	}
}

applicationcontext.xml配置

  <!-- 配置实例工厂bean -->
  <bean id="factory" class="com.bc.ioc.demo07.factory"/>
  <!-- 配置实例工厂方法bean -->
  <bean id="f_id" factory-bean="factory" factory-method="getid"/>
  <bean id="f_name" factory-bean="factory" factory-method="getname"/>
  <bean id="f_user" factory-bean="factory" factory-method="getuser"/>
  <!-- 注入对应的实例工厂方法bean -->
  <bean id="ioc_by_factory" class="com.bc.ioc.demo07.ioc_by_factory">
    <property name="id" ref="f_id"/>
    <property name="name" ref="f_name"/>
    <property name="user" ref="f_user"/>
  </bean>

测试类代码

public class ioc_test {
	private applicationcontext ctx;
	@before
	  public void load() {
		//读取applicationcontext.xml配置文件
		ctx = new classpathxmlapplicationcontext("applicationcontext.xml");
	}
	@test
	  public void factorytest() {
		ioc_by_factory ioc = (ioc_by_factory) ctx.getbean("ioc_by_factory");
		ioc.checkattr();
	}
}

控制台输出

id:1
----------------------------
name:实例工厂
----------------------------
user:1|实例工厂user|233
----------------------------
全部正确!!!

总结

以上就是本文关于浅谈spring ioc的注入方式及注入不同的数据类型的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网