java - How to use generics in spring? -
i have read lot of oline articles , couldnt find reply , have tried create right , not able it.
can help,how initialize generics in bean file , create work?
config file
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="collectiondemo" class="com.prashant.collections6.collectiondemo"> <constructor-arg index="0" type="string" value="google"/> <constructor-arg index="1" type="string" value="gooogle"/> </bean> </beans>
collectiondemo.java
public class collectiondemo<t> { private t id,phonenumber; public collectiondemo(t id, t phonenumber) { super(); this.id = id; this.phonenumber = phonenumber; } public t getid() { homecoming id; } public void setid(t id) { this.id = id; } public t getphonenumber() { homecoming phonenumber; } public void setphonenumber(t phonenumber) { this.phonenumber = phonenumber; } @override public string tostring() { homecoming "collectiondemo [id=" + id + ", phonenumber=" + phonenumber + "]"; } }
colleactionapp.java
package com.prashanth.collections6; import org.springframework.context.applicationcontext; import org.springframework.context.support.filesystemxmlapplicationcontext; public class colleactionapp { public static void main(string[] args) { applicationcontext app=new filesystemxmlapplicationcontext ("/src/main/java/com/prashanth/collections6/beans.xml"); collectiondemo<string> coll=(collectiondemo<string>) app.getbean("collectiondemo"); system.out.println(coll); } }
the issue you've posted in comments because of typo
<bean id="collectiondemo" class="com.prashant.collections6.collectiondemo">
should be
<bean id="collectiondemo" class="com.prashanth.collections6.collectiondemo">
assuming
package com.prashanth.collections6;
is right bundle name.
the "issue" generics
<constructor-arg index="0" type="string" value="google"/> <constructor-arg index="1" type="string" value="gooogle"/>
spring utilize type
specified match constructor arguments. class constructor's arguments not of type string
, of type t
, erase object
. either alter to
<constructor-arg index="0" type="object" value="google"/> <constructor-arg index="1" type="object" value="gooogle"/>
or remove type
altogether.
generics compile time concept. not exist @ runtime. spring uses reflection @ runtime generate beans. there's no type argument specify generic types in bean definitions.
java spring generics
No comments:
Post a Comment