• spring-ioc注解-理解2 零配置文件


    没有xml配置文件下的对象注入,使用到一个Teacher类,Config配置类,Test测试类。

    1、Teacher类

    import lombok.Data;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    
    
    import java.util.Date;
    
    //零配置文件
    @Data
    @Component("tea")
    //加载properties文件
    @PropertySource({"classpath:date.properties"})
    public class Teacher {
        @Value("1")
        private int id;
       // @Value("renzhe")
        @Value("${jdbc.url}")
        private String name;
        @Value("1500")
        private double salary;
        @Autowired
        private Date date;
    }

    2、配置类Config

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    import java.util.Date;
    
    //配置类相当于一个配置文件
    @Configuration
    //扫描的注解 扫描com.briup.spring的包以及他的子包子子包
    @ComponentScan("com.briup.spring")
    public class Config {
        //@Bean相当于bean标签 作用是把方法的返回值放入到容器中
        // 且默认方法的名字就是他的唯一标识 若想自定义名字则@Bean("名字")
    
        @Bean
        public Date date(){
            return  new Date();
        }
    
    }

    3、Test测试类

     @Test
        public void test2(){
              ApplicationContext app = new AnnotationConfigApplicationContext(Config.class);
              Teacher tea = app.getBean(Teacher.class);
              System.out.println(tea);
        }
  • 相关阅读:
    C++输入与输出
    数组与指针
    MFC+WinPcap编写一个嗅探器之零(目录)
    netty源码分析之揭开reactor线程的面纱(二)
    netty源码分析之揭开reactor线程的面纱(一)
    Vert.x 线程模型揭秘
    理解 RxJava 的线程模型
    Java RESTful 框架的性能比较
    Java借助CountDownLatch完成异步回调
    在 Java 中运用动态挂载实现 Bug 的热修复
  • 原文地址:https://www.cnblogs.com/jamers-rz/p/14056871.html
Copyright © 2020-2023  润新知