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();
        }
    }
  • 相关阅读:
    Http 请求处理流程
    ASP.NET 4.0: 请求验证模式变化导致ValidateRequest=false失效
    Android Animation学习笔记【转载】
    Http Handler 介绍
    对路径XXX的访问被拒绝(文件操作权限)的解决方法
    控制页面滚动条
    Sqlserver查询字段默认值
    Ajax基础
    浮动&定位
    定时器
  • 原文地址:https://www.cnblogs.com/zhlblogs/p/9273231.html
Copyright © 2011-2022 走看看