温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

spring中怎么利用构造函数实现注入

发布时间:2021-07-28 14:25:12 来源:亿速云 阅读:179 作者:Leah 栏目:编程语言

本篇文章给大家分享的是有关spring中怎么利用构造函数实现注入,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

一 通过构造函数注入

set注入的缺点是无法清晰表达哪些属性是必须的,哪些是可选的,构造注入的优势是通过构造强制依赖关系,不可能实例化不完全的或无法使用的bean。

二 举例

1Employee

package com.hsp.constructor;public class Employee {    private String name;    private int age;    public Employee(String name) {        System.out.println("Employee(String name) 函数被调用..");        this.name = name;        this.age = age;    }        public Employee(String name, int age) {        System.out.println("Employee(String name, int age) 函数被调用..");        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

2beans.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:context="http://www.springframework.org/schema/context";        xmlns:tx="http://www.springframework.org/schema/tx";        xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd";><!-- 配置一个雇员对象 --><bean id="employee" class="com.hsp.constructor.Employee"><!-- 通过构造函数来注入属性值 --><constructor-arg index="0" type="java.lang.String" value="大明" /></bean></beans>

3App1

package com.hsp.constructor;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App1 {  /**   * @param args   */  public static void main(String[] args) {    // TODO Auto-generated method stub    ApplicationContext ac=new ClassPathXmlApplicationContext("com/hsp/constructor/beans.xml");    Employee ee=(Employee) ac.getBean("employee");    System.out.println(ee.getName());  }}

三 测试结果

Employee(String name) 函数被调用..大明

以上就是spring中怎么利用构造函数实现注入,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI