Spring XML file - applicationContext.xml :
<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-3.0.xsd"> <bean id="helloBean" class="com.yiibai.hello.impl.HelloWorldImpl"> </beans>
package com.yiibai.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.yiibai.hello.HelloWorld; import com.yiibai.hello.impl.HelloWorldImpl; @Configuration public class AppConfig { @Bean(name="helloBean") public HelloWorld helloWorld() { return new HelloWorldImpl(); } }
一個簡單的Bean
package com.yiibai.hello; public interface HelloWorld { void printHelloWorld(String msg); }
package com.yiibai.hello.impl; import com.yiibai.hello.HelloWorld; public class HelloWorldImpl implements HelloWorld { @Override public void printHelloWorld(String msg) { System.out.println("Hello : " + msg); } }
package com.yiibai.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.yiibai.hello.HelloWorld; import com.yiibai.hello.impl.HelloWorldImpl; @Configuration public class AppConfig { @Bean(name="helloBean") public HelloWorld helloWorld() { return new HelloWorldImpl(); } }
使用 AnnotationConfigApplicationContext 載入您的JavaConfig類
package com.yiibai.core; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.yiibai.config.AppConfig; import com.yiibai.hello.HelloWorld; public class App { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); HelloWorld obj = (HelloWorld) context.getBean("helloBean"); obj.printHelloWorld("Spring Java Config"); } }
輸出結果
Hello : Spring Java Config