zoukankan      html  css  js  c++  java
  • Spring中基于java的配置

    Spring中为了减少XML配置,可以声明一个配置类类对bean进行配置,主要用到两个注解@Configuration和@bean

    例子:

    • 首先,XML中进行少量的配置来启动java配置:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        <context:component-scan base-package="com.demo.config"/>
    </beans>
    • 定义一个配置类,用@Configuration注解该类,等价于XML里的<beans>,用@Bean注解方法,等价于XML配置的<bean>,方法名等于beanId。代码如下:
    @Configuration
    public class SpringConfig {
        @Bean
        public Service service(){
            return new Service();
        }
        @Bean
        public Client client(){
            return new Client();
        }
    }
    • 其他Bean代码:
    public class Service {
        public String  sayHello(){
            return "HelloWord!";
        }
    }
    public class Client {
        @Autowired
        Service service;
        public void invokeService(){
            System.out.println("client invoke :" + service.sayHello());
        }
    }
    • 测试类
    public class Test {
    
        public static void main(String[] args) {
            ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
            Client client = context.getBean("client",Client.class);
            client.invokeService();
        }
    }

    加载XML中配置的beans和bean用:

    ApplicationContext ctx = new ClassPathXmlApplicationContext("config/bean.xml");// 读取bean.xml中的内容
    Counter c = ctx.getBean("client", Client.class);// 创建bean的引用对象

    • 运行结果

    • 写在最后

    SpringBean的创建和注入有三种,XML、注解、java配置文件。

    因为XML配置较为繁琐,现在大部分开始用注解和java配置,一般什么时候用注解或者java配置呢?

    基本原则是:全局配置用java配置(如数据库配置,MVC,redis等相关配置),业务Bean的配置用注解(@Service @Component@Repository@Controlle)。

  • 相关阅读:
    探讨游戏服务器设计
    找规律 0 1 3 8 22 64
    mysql 字段对比工具
    游戏开发者网站大集合
    sizeof struct 问题
    微软智力题
    python+requests——读取二进制文件并保存在本地——一个图片作为示例
    python+requests——检查响应头是否存在
    python+requests——读取二进制文件并保存在本地——一个应用程序作为示例
    python+requests——URL的编码和解码
  • 原文地址:https://www.cnblogs.com/foreverYoungCoder/p/8193738.html
Copyright © 2011-2022 走看看