第一次Spring Boot作业

2018-09-08  本文已影响0人  默写_0c03

第一次Spring Boot 作业

Student类

package com.niit.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * Created by jzy on 2018/9/3.
 */
Configuration
public class Student {

    @Value("张三")
    private String name;

    @Value("#{20-2}")
    private int age;

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

Teacher类

package com.niit.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * Created by jzy on 2018/9/3.
 */
@Configuration
public class Teacher {

    @Value("许老师")
    private String name;

    @Value("Spring Boot")
    private String subject;

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

Course类

package com.niit.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by jzy on 2018/9/3.
 */
@Component
public class Course {

    @Resource(name = "student")
    private Student student;

    @Resource(name = "teacher")
    private Teacher teacher;

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

}

QuickStartApplication类

package com.niit;

import com.niit.bean.Course;
import com.niit.bean.Hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class QuickstartApplication {

    public static void main(String[] args) {
        //启动Spring Boot ,并得到上下文对象
        ApplicationContext ac = SpringApplication.run(QuickstartApplication.class,args);
        System.out.println("使用Spring Boot 开始注入Course的bean,它由Teacher和Student的bean装配而成:");
        //从容器中获得Hello的对象hello
        Course course = (Course) ac.getBean("course");
        System.out.println(course.toString());
    }
}
上一篇下一篇

猜你喜欢

热点阅读