zoukankan      html  css  js  c++  java
  • spring之java配置

    java配置是通过@Configuration和@Bean来实现的

    @Configuration:声明当前类是一个配置类,相当于一个spring配置的xml文件

    @Bean:注解在方法上面,声明当前方法的返回值为一个Bean

    全局配置使用 java配置(如数据库相关配置,mvc相关配置),业务Bean的配置使用注解配置

    /**
     * 此处没有使用@Service声明Bean
     *
     * @author Holley
     * @create 2018-07-06 10:50
     **/
    public class HelloService {
        public String sayHello(String name) {
            return "Hello " + name + "!";
        }
    }
    /**
     * 此处没有使用@Service声明Bean,也没有使用@Autowired注入Bean
     *
     * @author Holley
     * @create 2018-07-06 11:32
     **/
    public class UseHelloService{
    
        private HelloService helloService;
    
    public void setSayHello(HelloService helloService) { this.helloService = helloService; }
    public String useSayHello(String name) { return helloService.sayHello(name); }
    }
    /**
     * 此处没有使用包扫描,因为所有的bean都在此类中定义了.
    * Bean的名称就是方法名 * 注入HelloService的Bean时,直接调用helloService()方法 *
    @author Holley * @create 2018-07-06 11:39 **/ @Configuration public class MyConfig { @Bean public HelloService helloService(){ return new HelloService(); } @Bean public UseHelloService useHelloService(){ UseHelloService useHelloService = new UseHelloService(); useHelloService.setSayHello(helloService()); return useHelloService; }
    // 另外一种注入方式,直接将HelloService作为参数给useHelloService().在spring容器中,只要存在某个Bean,就可以在另外一个Bean的声明方法的参数中注入。如:
        /* @Bean
        public UseHelloService useHelloService(HelloService helloService){ 
    UseHelloService useHelloService = new UseHelloService();
    useHelloService.setSayHello(helloService);
    return useHelloService;
    }*/
    }
    public class Test {
        public static void main(String[] args){
            // 使用AnnotationConfigApplicationContext作为spring容器
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
            UserHelloService userHelloService = context.getBean(UserHelloService.class);
            System.out.println(userHelloService.useSayHello("holley"));
            context.close();
        }
    }
  • 相关阅读:
    性能测试术语讲解
    Silverlight 部署
    C#数据库SQLServer查询、修改数据
    有一点点背
    Ajax与XMLHttpRequest对象
    ServletListener 之 监听HTTP会话
    JAVA中几种常见集合的使用实例
    [转]全面接触Java集合框架(二)
    自定义标签之 SimpleTag的开发
    jsp常用内置对象
  • 原文地址:https://www.cnblogs.com/zhlblogs/p/9273231.html
Copyright © 2011-2022 走看看