zoukankan      html  css  js  c++  java
  • 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");
        }
    }

    第五步:运行结果如下

    文件结构如下:

  • 相关阅读:
    微信端video去除最顶层播放
    MVC错误页面相关说明
    sublime使用
    linux或Mac下手动回滚代码
    用Python操作git命令
    利用pyinstaller打包加密Python项目
    进程、线程和协程的结合使用
    模块导入失败问题
    递归调用解压zip包或rar包
    随机验证码&发红包
  • 原文地址:https://www.cnblogs.com/beibidewomen/p/7383020.html
Copyright © 2011-2022 走看看