一般而言,Spring的依赖注入有三种:构造器注入、setter注入以及接口注入。本文主要讲构造器注入与setter注入。
1、构造器注入
为了让Spring完成构造器注入,我们需要去描述具体的类、构造方法并设置构造方法的对应参数。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
public class Role {
private Long id;
private String roleName;
private String note;
public Long getId() { return id; }
public void setId(Long id) { this .id = id; }
public String getRoleName() { return roleName; }
public void setRoleName(String roleName) { this .roleName = roleName; }
public String getNote() { return note; }
public void setNote(String note) { this .note = note; }
public Role(String roleName, String note) { this .roleName = roleName; this .note = note; }
public Role() {
}
public void run() { System.out.println( "roleName:" + roleName + ";" + "note:" + note); } } |
这个时候是没有办法利用无参的构造方法去创建对象的,为了使Spring能正确创建这个对象,需要在xml文件中加入如下bean:
1 2 3 4 |
< bean id = "role1" class = "com.ssm.chapter.pojo.Role" > < constructor-arg index = "0" value = "总经理" /> < constructor-arg index = "1" value = "公司管理者" /> </ bean > |
其中,constructor-arg元素用于定义类构造方法的参数,index用于定义参数的位置,而value是设置值,通过这样定义spring便知道使用Role(String, String)这样的构造方法去创建对象了。
2、使用setter注入
setter注入是Spring最主流的注入方式,它消除了使用构造器注入多个参数的可能性,可以把构造参数声明为无参的,然后使用setter注入为其设置对应的值。需要注意的是,如果类中没有构造函数,JVM会默认创建一个无参构造函数。xml代码清单如下:
1 2 3 4 |
< bean id = "role2" class = "com.ssm.chapter.pojo.Role" > < property name = "roleName" value = "高级工程师" /> < property name = "note" value = "重要人员" /> </ bean > |
接着编写测试类即可:
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-cfg.xml");
Role role = (Role) ctx.getBean("role2");
role.run();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://www.cnblogs.com/pusan/p/12174123.html
查看更多关于Spring Bean常用依赖注入方式详解的详细内容...