美文网首页
JavaEE - Spring Boot组件和注入

JavaEE - Spring Boot组件和注入

作者: tigerAndBull | 来源:发表于2018-09-03 11:01 被阅读0次

学生类

@Configuration
public class Student {

    @Value("wenhu an")
    private String name;

    @Value("1602753101")
    private String studentId;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", studentId='" + studentId + '\'' +
                '}';
    }
}

教师类

@Configuration
public class Teacher {

    @Value("moqi xu")
    private String name;

    @Value("111")
    private String teacherId;

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", teacherId='" + teacherId + '\'' +
                '}';
    }
}

课程类

/**
 * @author tigerAndBull
 * 使用@Component注解标注一个类,这个类的对象为可被Spring容器注入,是一个单例的bean
 * 注入分为构造器注入和setter注入
 * 依赖注入和AOP是Spring的两大特性
 */
@Component
public class Course {

    @Resource
    private Student student;

    @Resource
    private Teacher teacher;

    @Override
    public String toString() {
        return "Course{" +
                "学生:" + student.toString() +
                ", 教师:" + teacher.toString() +
                '}';
    }
}

Main

/**
 * @author tigerAndBull
 * 使用@SpringBootApplication注解的类,是启动主类,一般放在项目顶层包下
 * 它是一下内容的综合,
 * 1 @Configuration 标记一个类来作为bean定义的应用程序上下文的资源
 * 2 @EnavleAutoCongfigutation 告诉Spring Boot开始加载基于类路径下的配置信息,beans,各种属性配置
 * 3 @ComponententScan 告诉Spring寻找其他组件,配置,以及业务层类,最前面才能加载到所有的类
 */
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {

        ApplicationContext ac = SpringApplication.run(DemoApplication.class, args);
        Course course = (Course) ac.getBean("course");

        System.out.println(course.toString());
    }
}

运行结果


image.png

相关文章

网友评论

      本文标题:JavaEE - Spring Boot组件和注入

      本文链接:https://www.haomeiwen.com/subject/dxdbwftx.html