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);
        }
  • 相关阅读:
    Android Things专题 1.前世今生
    用Power BI解读幸福星球指数
    [leetcode]Simplify Path
    字段的划分完整的问题
    k-means算法MATLAB和opencv代码
    【Oracle】RAC下的一些经常使用命令(一)
    Java中经常使用缓存Cache机制的实现
    jenkins环境自动部署
    jenkins环境搭建
    springboot单元测试@test的使用
  • 原文地址:https://www.cnblogs.com/jamers-rz/p/14056871.html
Copyright © 2011-2022 走看看