Spring构造方法注入

 

默认情况下applicationContext.xml文件中配置的程序可以通过Spring自动实例化对象。

示例:

package com.javaketang.test;

public class  User{

   privete String name;//用户名
   
   private Intger age;//年龄

    
    public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

    public Intger getAge() {
		return age;
	}

	public void setAge(Intger age) {
		this.age = age;
	}

	@Override
	public String toString() {
		
		return "名字为:" + name+";年龄:"+age;
	}



}

 无参构造方法配置:

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


<bean id="user" class="com.javaketang.com.User"/>



</beans>

 

编写测试类

public static void main(String[] args) {

		ApplicationContext ap = new ClassPathXmlApplicationContext("application-config.xml");

		User u=ap.getBean("user",User.class);

        u.setName("张三");
        u.setAge(25);
		
		System.out.println(u);
	}

将会输出以下结果:

名字为:张三;年龄:25

 

但是自动实例化对象调用的是无参构造方法,如果没有提供无参构造方法,就会报错。

有参构造方法配置:

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


<bean id="user" class="com.javaketang.com.User">
<-! 可以不用指定类型,因为Spring可以自动匹配类型 -->
<constructor-arg value="张三" type="java.lang.String"/>
<constructor-arg value="25" type="java.lang.Intger"/>
</bean>



</beans>

编写测试

public static void main(String[] args) {

		ApplicationContext ap = new ClassPathXmlApplicationContext("application-config.xml");

		User u=ap.getBean("user",User.class);

        
		System.out.println(u);
	}

将会输出以下结果:

名字为:张三;年龄:25

 

注意:在你提供有参方法是一定要提供一个无参构造方法。

 

中智软件科技学校

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值