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);
    }
原文地址:https://www.cnblogs.com/jamers-rz/p/14056871.html