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();
        }
    }
  • 相关阅读:
    Java多态
    推荐TED演讲:20岁光阴不再来(Why 30 is not the new 20)
    HDU 5305 Friends (DFS)
    C#高级编程八十一天----捕获异常
    Amazon EC2安装mysql多实例并配置主从复制
    python coding style guide 的高速落地实践
    Tomcat 在win7/win8 系统下tomcat-users.xml.new(拒绝访问)解决方法
    jsp+oracle实现数据库内容以表格形式在前台显示(包含分页)
    JSP/SERVLET入门教程--Servlet 使用入门
    解决系统打开CHM文件无法正常显示
  • 原文地址:https://www.cnblogs.com/zhlblogs/p/9273231.html
Copyright © 2011-2022 走看看