怎么在spring中通过构造函数注入
这篇文章给大家介绍怎么在spring中通过构造函数注入,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

创新互联公司是创新、创意、研发型一体的综合型网站建设公司,自成立以来公司不断探索创新,始终坚持为客户提供满意周到的服务,在本地打下了良好的口碑,在过去的十余年时间我们累计服务了上千家以及全国政企客户,如成都宣传片制作等企业单位,完善的项目管理流程,严格把控项目进度与质量监控加上过硬的技术实力获得客户的一致称扬。
一 通过构造函数注入
set注入的缺点是无法清晰表达哪些属性是必须的,哪些是可选的,构造注入的优势是通过构造强制依赖关系,不可能实例化不完全的或无法使用的bean。
二 举例
1 Employee
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;
}
}2 beans.xml
3 App1
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中通过构造函数注入就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
文章题目:怎么在spring中通过构造函数注入
文章链接:http://www.jxjierui.cn/article/gcophs.html


咨询
建站咨询
