第一步:编写接口
HelloWorld.java
package com.xuzhiwen.spring3; public interface HelloWorld { public abstract void printHelloWorld(String msg); }
第二步:编写实现类
package com.xuzhiwen.spring3; public class HelloWorldImpl implements HelloWorld{ @Override public void printHelloWorld(String msg) { System.out.println("hello: " + msg); } }
第三步:编写javaconfig 配置等效的Java
AppConfig.java
package com.xuzhiwen.spring3; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean(name="hellowrold") public HelloWorld getHelloWorld(){ return new HelloWorldImpl(); } }
该文件等效于:
<bean id="helloworld" class="com.xuzhiwen.spring2.HelloWorldImpl" />
第四步:编写测试类
package com.xuzhiwen.spring3; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestHelloWorld { public static void main(String[] args) { ApplicationContext app = new AnnotationConfigApplicationContext(AppConfig.class); HelloWorld helloworld = (HelloWorld) app.getBean("hellowrold"); helloworld.printHelloWorld("good boy"); } }
第五步:运行结果如下
文件结构如下: