这里我们定义一个bean,里面有两个属性name和number。
本文来自www.itxxz.com
- package com.itxxz.user.bean;
- public class Sport {
- private String name;
- private int number;
- }
然后配置applicationContext.xml,这里通过两种方式进行赋值,一个是通过value属性,一个是通过value标签
- <!-- 体育运动1 -->
- <bean id="sport1" class="com.itxxz.user.bean.Sport">
- <constructor-arg value="足球"></constructor-arg>
- <constructor-arg>
- <value>11</value>
- </constructor-arg>
- </bean>
但是,如果不小心,就会报一个错:
Multiple annotations found at this line:
- No constructor with 2 arguments defined in class
'com.itxxz.user.bean.Sport'
如下图:
这是由于在bean中没有两个参数的构造方法,只需要新增就可以了
- public Sport(String name, int number) {
- super();
- this.name = name;
- this.number = number;
- }
在加载bean的时候我们既可以通过bean的id,也可以通过类加载,就像下方代码:
- public static void main(String[] args) {
- ApplicationContext act = new ClassPathXmlApplicationContext(
- "applicationContext.xml");
- Sport s1 = act.getBean(Sport.class);
- System.out.println(s1);
- }
运行结果:
通过上述代码及结果可以看出,通过类加载,不需要类型强转,但是也有一个弊端。
如果在xml文件中再定义一个id为sport2的bean配置,则会因为加载的类相同,导致spring无法判断加载那一个而报错,
Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.itxxz.user.bean.Sport] is defined: expected single matching bean but found 2: sport2,sport1
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:365)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:968)
at com.itxxz.test.HelloWorld.main(HelloWorld.java:20)
IT学习者(www.itxxz.com)
所以应用时建议通过bean来加载。
Sport sport1 = (Sport)act.getBean("sport1");
通过上述代码可知,spring可以实现构造参数的赋值。但是,bean中赋值的字段对应的是不是javabean中的属性呢?
我们在Sprot中添加如下两个个setter方法,如下:
- private String name;
- private int number;
- public void setName(String name) {
- this.name = name;
- }
- public void setNumber2(int num) {
- this.number = num;
- }
在bean配置文件中新增
- <bean id = "sport2" class="com.itxxz.user.bean.Sport">
- <property name="name" value="篮球"></property>
- <property name="number2" value="4"></property>
- </bean>
从结果可以看到,name和number都被赋了值。
对于name赋值是意料之中,可是怎么通过number2的setter给number赋值了呢?
这是由于bean中的property属性对应的是setter中的字段,如果是setAge,那么property的name为age,如果是setTime,name为time,这就是spring的反射机制。
http://www.itxxz.com/a/gaoji/2015/0127/spring_constructor_arg.html