zoukankan      html  css  js  c++  java
  • 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);
        }
  • 相关阅读:
    .Net 多线程小结
    VIM 入门操作
    C语言中的数据
    对scanf和printf的研究!!
    C语言常用的编程规范
    ORACLE GOLDEN GATE oracle同步数据至kafka
    mysql5.7关于使用到OR是否会用到索引并提高查询效率的探讨
    sysbench安装
    percona数据库监控工具的安装部署
    redhat6 快速部署percona
  • 原文地址:https://www.cnblogs.com/jamers-rz/p/14056871.html
Copyright © 2011-2022 走看看