Spring-IOCを使用するための簡単な参照:
スプリングIOCおよび範囲の豆の属性の単純なインスタンスの分析
1.設定方法からさまざまなデータ型を注入します
テストクラスコード(設定された方法で注入されたプロパティは、設定された方法で追加する必要があります)
/** indection set method*/public class ioc_by_set {/** Inject Integer Type Parameter*/private Integer id;/** Inject String type parameter*/private string name;/** Inject Entityユーザー設定;/**マップの注入キーバリューペア*/プライベートマップ<オブジェクト、オブジェクト>マップ;/**挿入プロパティタイプ*/プライベートプロパティプロパティ;/**プライベートストリングemptyValue*/private string nullvalue = "";/**注入プロパティがすべて正しいかどうかを返信するかどうかを返すnullvalue = ";/** false;} else {system.out.println( "id:" + id);}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- name);}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------配列) {System.out.println(object.toString());}}System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- {system.out.println( "set:"); for(object object:set) {System.out.println(object.toString());}}System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- {system.out.println(entry.getKey() + "|" + entry.getValue());}}System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ entry.getValue());}}System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- setName(string name){this.name = name;} public void setuser(user user){this.user = user;} public void setArray(object [] array){this.array = array;} public void setlist(list <object> list){this.list = list = list;} public void set(set <オブジェクト> set;} setMap(map <object、object> map){this.map = map;} public void setProperties(properties Properties){this.properties = properties;} public void setemptyValue(string emptyvalue){this.emptyvalue = emptyvalue;} public void setnullue;ApplicationContext.xml構成
<! - インジェクションの設定 - > <bean id = "ioc_by_set"> <! - インジェクションID属性 - > <プロパティ名= "id" value = "1"/> <! - <! - <![cdata []]>タグを使用してxml特殊文字を処理する<! <値> <![cdata [P&G]]> </value> </property> <! - 内部ビーンインジェクションの定義 - > <プロパティ名= "user"> <bean> <プロパティ名= "id" value = "1"/> <プロパティ名= "username" value = "internal bean"/> <プロパティnam name = "array"> <array> <! - define array要素 - > <value> array01 </value> <value> array02 </value> <balue> array03 </value> </array> </property> <! - Inject List-> <Property name = "list"> <> < <value> list03 </value> </list> </property> <! - Inject set type-> <property> <プロパティ - > <value> list02 </value> <value> list03 </value> </list> </property> <!-インジェックセットタイプ - > <プロパティname = "> <set> <set> <set> <> <> <> <> <value> set02 </value> <value> set03 </value> </set> </propertion> < </key> <value> mapvalue02 </value> </entry> </map> </property> <! - Injectプロパティタイプ - > <プロパティname = "プロパティ"> <props> <props> <! - プロパティのキー値ペアを定義する - > <prope = "propkey1"> propvalue1 </prop> propkey2 </prop </proppkey2 </proppkey2 </proppkey2 </prop < string-> <プロパティ名= "emptyvalue"> <値> </value> </property> <! - null値を注入 - > <プロパティname = "nullvalue"> <null/> </property> </bean>
テストコード
public class ioc_test {private applicationcontext ctx; @before public void load(){// read applicationcontext.xml configuration file ctx = new classpathxmlapplicationcontext( "applicationContext.xml");}@test public void settest(){ioc_by_set ioc =(ioc_by_set) ctx.getbean( "ioc_by_set"); ioc.checkattr();}}}コンソールの結果:
id:1----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 3-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ! !
2。建設方法を通じてさまざまなタイプの属性を注入します
注:JDK1.8バージョンを使用する場合は、バージョン4.x以上にスプリング関連のJARパッケージをアップグレードしてください。そうしないと、互換性のないコンストラクターが注入されます。
クラスコードをテストします
/**コンストラクターによるインジェクションの例list;}/**注入が成功したかどうかを確認*/public boolean checkattr(){if(id == null){return false;} else {system.out.println( "id:" + id) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + "|" + user.getusername + " + user.getPassWord());}System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------真実;}}ApplicationContext.xml構成
<! - Constructor-ARG値= "P&G"/> <! - 噴射オブジェクト - > <bean id = "ioc_by_constructor"> <! - 噴射オブジェクト - > <bean> <constructor-arg value = "1" type = "Java.lang.integer"/> <! - Injed string-> <construction-arg value-> < <constructor-arg> <! - 組み込みオブジェクト - > <bean> <constructor-arg値= "1"/> <constructor-arg値= "内部ビーン"/> <constructor-arg value = "666"/> </bean> </constructor-arg> < <value> list03 </value> </list> </constructor-arg> </bean>
テストコード:
public class ioc_test {private applicationcontext ctx; @before public void load(){// read applicationContext.xml configuration file ctx = new classpathxmlapplicationcontext( "applicationcontext.xml");}@test public void constructustortest(){ioc_by_by_constructorioc_by_by_by_by_by_by_by_by_by_by_by_by_by_by_by_by_by_by_by_by_by ctx.getbean( "ioc_by_constructor"); ioc.checkattr();}}}コンソールの結果:
id:1----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ! !
3。自動噴射(自動アセンブリ)
自動アセンブリはいくつかのコードを節約できますが、それを使用することはお勧めしません
テストクラスコード:
/**自動アセンブリインジェクション*/パブリッククラスIOC_BY_AUTO {プライベートユーザーユーザー;/**注入が成功しているかどうかを確認*/public boolean checkattr(){if(user == null){return false;} else {system.out.println( "user:" + user.getid() + "|" +ユーザー。 user.getPassWord();} System.out.println( "recurt !!!"); return true;}/**自動アセンブリ属性には設定されたメソッドを設定する必要があります*/public void setuser(user user){this.user = user;}}}ApplicationContext.xml構成
<! - 自動アセンブリによって取得された豆 - > <bean id = "user name"> <property name = "id" value = "1"/> <プロパティ名= "username name" value = "auto-assembly"/> <property name "value =" 233 "/> </bean> <!-bean autowire:byname autowire:byname autowire:byname of the clacesクラスのタイプ。複数の豆と一致する場合、クラスのコンストラクターパラメータータイプに従って、例外コンストラクターが対応する豆と一致します。いいえ。デフォルト、自動アセンブリのデフォルトが使用されないことを意味します。上部ラベルのデフォルトアウトワイヤプロパティによって決定<beans> - > <bean id = "ioc_by_auto" autowire = "byname"> </bean>
テストコード
public class ioc_test {private applicationcontext ctx; @before public void load(){// read applicationcontext.xml configuration file ctx = new classpathxmlapplicationcontext( "applicationContext.xml");}@test public void autotest(){ioc_by_auto ioc_by_auto) ctx.getbean( "ioc_by_auto"); ioc.checkattr();}}}コンソールの結果
ユーザー:1 |自動アセンブリ| 233は正しいです! ! !
上記は、bynameモードを使用しています。他のモードの構成コードが示されており、テストは実行されません。
4。pネームスペースを使用して属性を注入します
クラスコードをテストします
/** p namespaceを使用したインジェクション*/public class ioc_by_p {private integer id; private string name; private user user;/**注入が成功したかどうかを確認*/public boolean checkattr(){if(id == null){return false;} else {system.out.out.println( "id:" + " +" + " id);}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- name);}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- id){this.id = id;} public void setname(string name){this.name = name;} public void setuser(user user){this.user = user;}}}ApplicationContext.xml構成
<! - p namespaceを使用してさまざまなタイプのプロパティを挿入 - > <bean id = "user2"> <プロパティ名= "id" value = "1"/> <Username "value =" P "/> <プロパティ名="パスワード "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 "値"値 " P:user-ref = "user2"> </bean>
テストコード
public class ioc_test {private applicationcontext ctx; @before public void load(){// read approachContext.xml configuration file ctx = new classpathxmlapplicationcontext( "applicationContext.xml");}@test public void ptest(){ioc_by_p ioc =(ioc_by_p) ctx.getbean( "ioc_by_p"); ioc.checkattr();}}}コンソールの結果
id:1----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ! !
5。注釈法を使用して注入します
Springは、3.0後に注釈ベースの注入を提供しました。
1.@自動アセンブリ作業を完了するためのメンバー変数、メソッド、およびコンストラクターのAutowired-Annotation。使用することはお勧めしません。
2. @autowiredで @qualifier-combined同じタイプの複数の豆のアセンブリを解決する
3。 @Resource-JSR-250標準注釈、関数は@Autowiredと同等ですが、@AutowiredはByTypeに従って自動的に注入されますが、@ResourceはデフォルトでByNameに従って自動的に注入されます。
4. @postconstruct -annotation @postconstructをメソッドに追加すると、このメソッドはBeanが初期化された後にスプリングコンテナによって実行されます。
5. @predestroy-add annotation @predestroyメソッドでは、この方法は、Beanが初期化された後にSpring Containerによって実行されます。
6. @componentのみの@componentアノテーションを対応するクラスに追加すると、クラスはBeanとして定義されます。使用することはお勧めしません。 @Repository、@Service、@Controllerの3つの洗練されたタイプを使用することをお勧めします
@RepositoryストレージレイヤーBean
@Service Business Layer Bean
@controllerディスプレイレイヤービーン
7.@scope-define beanの範囲
最初にApplicationContext.xmlを設定して、注釈を有効にします
<! - パッケージの注釈付きクラスをスキャン - > <コンテキスト:Component-ScanSycanベースパッケージ= "com.bc.ioc.demo05"/>
エンティティビーンアノテーション
@RepositoryPublic classユーザー{private integer id = 1; private string username = "annotation joction"; private string password = "233"; public user(){super();} public user(integer id、string username、string password){super(); this.id = id; thisername = username; id;} public string getUsername(){return username;} public string getPassword(){return password;} public void setid(integer id){this.id = id;} public void setusername(string username){this.username = username;} public voidword(} public setPassword;}テストクラスコードアノテーション
/** annotationsを使用して属性を注入*/@service( "ioc_by_annotation")public class ioc_by_annotation {@resource private user user; public void setuser(this.user){this.user = user;}/**インジェクションが成功したかどうかを確認*/ {system.out.println( "user:" + user.getId() + "|" + user.getUsername() + "|" + user.getPassWord());} system.out.println( "recurt !!!"); return true;}}}テストコード
public class ioc_test {private applicationcontext ctx; @before public void load(){// read applicationcontext.xml configuration file ctx = new classpathxmlapplicationcontext( "applicationContext.xml");}@public void annotationtest(){ioc_by_annotation ioc_annotation ctx.getbean( "ioc_by_annotation"); ioc.checkattr();}}}コンソール出力
テスト後、注釈注入を使用します。 ApplicationContext.xmlが他の注入方法で構成されている場合、エラーが報告され、他の注入方法も異常になります。
ユーザー:1 |注入注入| 233は正しいです! ! !
6。静的工場法を構成することによる豆噴射
静的工場コード
/** static Factory*/public class staticFactory {public static integer getId(){return 1;} public static string getname(){return "static Factory";} public static user getUser(){return newユーザー(1、 "ファクトリーユーザー"、 "666");}}}クラスコードをテストします
/**静的工場からのインジェクション*/パブリッククラスIOC_BY_STATICAFTORY {private Integer id; private integer name; private user user;/**注入が成功したかどうかを確認*/public boolean checkattr(){if(id == null){return false;} else {system.out.out.println( "id:" + " +" + id);}System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- name);}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- id){this.id = id;} public void setname(string name){this.name = name;} public void setuser(user user){this.user = user;}}}ApplicationContext.xml構成
< id = "ioc_by_staticfactory"> <プロパティ名= "id" ref = "factory_id"/> <プロパティ名= "name ref =" factory_name "/> <プロパティ名=" user "ref =" factory_user "/> </bean> </bean>
テストコード
public class IoC_Test {private ApplicationContext ctx;@Before public void load() {//Read applicationContext.xml configuration file ctx = new ClassPathXmlApplicationContext("applicationContext.xml");}@Test public void staticFactoryTest() {IoC_By_StaticFactory ioc = (IoC_By_StaticFactory) ctx.getbean( "ioc_by_staticfactory"); ioc.checkattr();}}}コンソール出力結果
id:1----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ! !
7。例の工場法による注入
静的工場との違いは、インスタンスファクトリが静的ではないことです。そのメソッドを構成する前に、最初に新しいインスタンスファクトリーオブジェクトが必要です。新しいオブジェクトは、春にも管理されています。
工場コード
/** Instance Factory*/public class Factory {public integer getId(){return 1;} public string getName(){return "Instance Factory";} public user getUser(){return new user(1、 "instance factory user"、 "233");}}}クラスコードをテストします
/** Instance Factory Injection*/public class IOC_BY_FACTORY {private Integer id; private string name; private user user;/**注入が成功したかどうかを確認*/public boolean checkattr(){if(id == null){return false;} els {system.out.out.println( "id:" + " +" + id);}System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- name);}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- id){this.id = id;} public void setname(string name){this.name = name;} public void setuser(user user){this.user = user;}}}ApplicationContext.xml構成
<! - Instance Factory Beanの構成 - > <Bean Id = "Factory"/> <! - Instance Factory Method Bean - > <Bean id = "f_id" Factory-bean = "Factory" Factory-method = "getid"/> <bean id = "f_name" factory-bean = "factory"> "/<bean"> <bean id " Factory-bean = "Factory" Factory-Method = "getuser"/> <! - 対応するインスタンスの工場メソッドBeanを注入 - > <bean id = "ioc_by_factory"> <プロパティ名= "id" ref = "f_id"/> <プロパティ名= "name" ref = "f_name"/> <プロパティ= "ユーザー" ref = "ref ="
クラスコードをテストします
public class IoC_Test {private ApplicationContext ctx;@Before public void load() {//Read applicationContext.xml configuration file ctx = new ClassPathXmlApplicationContext("applicationContext.xml");}@Test public void factoryTest() {IoC_By_Factory ioc = (IoC_By_Factory) ctx.getbean( "ioc_by_factory"); ioc.checkattr();}}}コンソール出力
id:1----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ! !
要約します
上記は、Spring IOCの注入方法とさまざまなデータ型の注入に関するこの記事の簡単な議論に関するものです。私はそれが誰にでも役立つことを願っています。興味のある友人は、このサイトの他の関連トピックを引き続き参照できます。欠点がある場合は、それを指摘するためにメッセージを残してください。このサイトへのご支援をありがとうございました!