| Newsletter |
Example On Spring Autowiring by Autodetect
Spring » on Feb 8, 2012 { 6 Comments } By Sivateja
Let us see the example on spring Autowiring with autowire as autodetect. Actually spring autowire=”autodetect” frist will works as Spring Autowiring constructor if not then works as Spring Autowiring byType, byType means setter injection right hope you remember 🙂 well will see the example..
Example On Spring Autowiring autodetect
Files required…
- ClientLogic.java
- Book.java
- Categories.java
- spconfig.xml
Book.java
package java4s;
public class Book {
private String bookname;
private int bookprice;
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public int getBookprice() {
return bookprice;
}
public void setBookprice(int bookprice) {
this.bookprice = bookprice;
}
}Categories.java
package java4s;
public class Categories {
private String name;
private Book bk;
public Categories(Book bk)
{
this.bk=bk;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show()
{
System.out.println("Categories name :"+name);
System.out.println("Book name :"+bk.getBookname()+" and Book Price :"+bk.getBookprice());
}
}ClientLogic.java
package java4s;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class ClientLogic {
public static void main(String[] args)
{
Resource res = new ClassPathResource("spconfig.xml");
BeanFactory factory = new XmlBeanFactory(res);
Object o = factory.getBean("id1");
Categories wb = (Categories)o;
wb.show();
}
}spconfig.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <beans> <bean id="id1" class="java4s.Categories" autowire="autodetect"> <property name="name" value="General Books" /> </bean> <bean id="SomeThing" class="java4s.Book"> <property name="bookname" value="The Kids" /> <property name="bookprice" value="300" /> </bean> </beans>
![]() | ![]() |
You Might Also Like
::. About the Author .:: | ||
![]() | ||
Comments
6 Responses to “Example On Spring Autowiring by Autodetect”



Is autowire=”autodetect” is working with Spring 3.0 ??
Can we autowire Collections(Map,list,Set etc)?
If so, can you please provide a small example.
Hi Siva Please check the statement
Actually spring autowire=”autodetect” frist will works as Spring Autowiring constructor if not then works as Spring Autowiring byType,
But, it is reverse
Actually spring autowire=”autodetect” frist will works as Spring Autowiring byType if not then works as Spring Autowiring constructor ,
Categories class didn’t contain setter method for Book class. Is it going to work if only constructor for Book is present ?
no, it wont work, there must be both setter and constructor.
It will work …no need to have setter