Spring Bean常用依赖注入方式详解
一般而言,Spring的依赖注入有三种:构造器注入、setter注入以及接口注入。本文主要讲构造器注入与setter注入。
1、构造器注入
为了让Spring完成构造器注入,我们需要去描述具体的类、构造方法并设置构造方法的对应参数。
代码如下:
publicclassRole{ privateLongid; privateStringroleName; privateStringnote; publicLonggetId(){ returnid; } publicvoidsetId(Longid){ this.id=id; } publicStringgetRoleName(){ returnroleName; } publicvoidsetRoleName(StringroleName){ this.roleName=roleName; } publicStringgetNote(){ returnnote; } publicvoidsetNote(Stringnote){ this.note=note; } publicRole(StringroleName,Stringnote){ this.roleName=roleName; this.note=note; } publicRole(){ } publicvoidrun(){ System.out.println("roleName:"+roleName+";"+"note:"+note); } }
这个时候是没有办法利用无参的构造方法去创建对象的,为了使Spring能正确创建这个对象,需要在xml文件中加入如下bean:
其中,constructor-arg元素用于定义类构造方法的参数,index用于定义参数的位置,而value是设置值,通过这样定义spring便知道使用Role(String,String)这样的构造方法去创建对象了。
2、使用setter注入
setter注入是Spring最主流的注入方式,它消除了使用构造器注入多个参数的可能性,可以把构造参数声明为无参的,然后使用setter注入为其设置对应的值。需要注意的是,如果类中没有构造函数,JVM会默认创建一个无参构造函数。xml代码清单如下:
接着编写测试类即可:
ApplicationContextctx=newClassPathXmlApplicationContext("spring-cfg.xml");
Rolerole=(Role)ctx.getBean("role2");
role.run();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。