版权声明:本文为博主原创文章,如需转载请标注转载地址。
博客地址:
Spring bean提供了3中注入方式:属性注入和构造方法注入
1、属性注入:
12 3 4
属性注入方式,要求属性提供呢setXxx方法。上面提供的是普通属性注入,如果要注入对象属性,可以这样
12 3 4 5
我们看到第三个属性dept,是一个Dept类型的属性,可以通过ref来引用一个已定义的Dept类型的dept对象。
1 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");2 User user=context.getBean("user", User.class);3 System.out.println(user.getUsername());4 System.out.println(user.getDept().getName());
结果我们可以看到
caoyc信息部
除了可以使用ref来引用外部对象外,我们也可以在user对象内部声明一个Dept对象
12 3 4 5 106 97 8
2、使用构造器注入
假如,有一个User类
package com.proc.bean;public class User { private int id; private String username; private int age; private double slary; public User() { } public User(int id, String username) { this.id = id; this.username = username; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", age=" + age + ", slary=" + slary + "]"; }}
这里使用的是: public User(int id, String username)构造方式
这里使用的是下标方式,这里省略了index属性。index属性从0开始。上面的代码相当于
12 3 4
假设有这样的两个构造方式
1 public User(int id, String username, int age) { 2 this.id = id; 3 this.username = username; 4 this.age = age; 5 } 6 public User(int id, String username, double slary) { 7 this.id = id; 8 this.username = username; 9 this.slary = slary;10 }
配置bean
12 6 73 4 5 8 9 10 11
测试代码
1 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");2 User user=context.getBean("user",User.class);3 System.out.println(user);4 5 User user2=context.getBean("user2",User.class);6 System.out.println(user2);
输出结果
1 User [id=1, username=caoyc, age=0, slary=18.0]2 User [id=1, username=caoyc, age=0, slary=1800.0]
这里都是调用的public User(int id, String username, double slary)这个构造函数。那么怎么调用public User(int id, String username, int age)这个构造函数呢?
方法是,在这里我们需要使用到type属性,来指定参数的具体类型
12 3 4 5
输出结果
1 User [id=1, username=caoyc, age=18, slary=0.0]2 User [id=1, username=caoyc, age=0, slary=1800.0]
【其它说明】
1、如果value属性是基本属性直接使用
2、如果valeu属性是其它类型,需要使用ref引用外部类型或使用内部定义方式
3、如果value属性中包含了xml特殊字符,需要使用CDATA来。例如:
12 ]]> 3