Friday, August 17, 2012

IOC : Java-based configuration and autowiring


Dean.java:
package com.lnn.ioc;

public class Dean {
      private String name;

      public String getName() {
            return name;
      }

      public void setName(String name) {
            this.name = name;
      }
}
MyBean.java:
package com.lnn.ioc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class MyBean {
      @Autowired
      @Qualifier("hello")
      private Dean dean = null;

      public Dean getDean() {
            return dean;
      }

      public void setDean(Dean dean) {
            this.dean = dean;
      }
}
JavaBeanConfig.java:
package com.lnn.ioc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.lnn.ioc.Dean;
import com.lnn.ioc.MyBean;

@Configuration
public class JavaBeanConfig {
      @Bean
      public MyBean bean() {
            return new MyBean();
      }

      @Bean
      public Dean dean() {
            Dean dean = new Dean();
            dean.setName("dean");
            return dean;
      }

      @Bean
      public Dean hello() {
            Dean dean = new Dean();
            dean.setName("hello");
            return dean;
      }
}
ioc.xml:
<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"    
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd">
      <context:annotation-config/>
      <context:component-scan base-package="com.lnn.ioc.config"/>
</beans>
Test.java:
package com.lnn.ioc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
      public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
            MyBean bean = context.getBean("bean", MyBean.class);
            System.out.println(bean.getDean().getName());
      }
}

No comments:

Post a Comment