spring 通过JavaConfig完成spring.xml文件的功能

第一步:编写接口

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");
    }
}

第五步:运行结果如下

 

文件结构如下:

 

posted @ 2017-08-17 17:31  beibidewomen  阅读(232)  评论(0编辑  收藏  举报