Announcement Announcement Module
Collapse
No announcement yet.
Di Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Di

    I am trying to use @Autowired like the following -

    applicationContext.xml
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:p="http://www.springframework.org/schema/p"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    	http://www.springframework.org/schema/context 
    	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    
    	<context:annotation-config />
    
    	<bean id="hello" class="org.tut.ioc.BeanImpl" />
    
    </beans>

    Code:
    public class IOCDriver {
    	@Autowired
    	BeanInterface hello;
    
    	public static void main(String[] args) {
    		IOCDriver driver = new IOCDriver();
    		driver.process();
    	}
    	
    	public void process(){
    			hello.sayHello();
    	}
    
    }
    and it seems that hello is not geting initialized. Even the spring IOC is not working. But if I change the main method and try to use hello using ApplicationContext it works-

    Code:
    		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    		BeanInterface hello = (BeanInterface) ac.getBean("hello");
    		hello.sayHello();
    Can someone please explain....

  • #2
    probably need to set the base scan package:

    base-package="your.package"

    Comment


    • #3
      In your first approach you are not initializing spring.

      Juan

      Comment


      • #4
        Autowiring doesn't affect newing objects. To get it to work, add

        Code:
        <bean id="iocDriver" class="IOCDriver"/>
        to your config, and change the main method to

        Code:
        public static void main(String... args) throws Exception {
            ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            IOCDriver driver = (IOCDriver)ac.getBean("iocDriver");
            driver.process();
        }

        Comment

        Working...
        X