Spring注解驱动开发

第一步:添加依赖

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.1.5.RELEASEversion>
        dependency>

定义一个Bean对象,用于注入给Spring容器

public class Student {

    private String name;

    private String age;

    public Student() {
        System.out.println("Student对象初始化!");
    }

    public Student(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public void study(){
        System.out.println("学习Java");
    }
}

配置类:

@Configuration
public class HellConfig {
    @Bean
    public Student getStudent() {
        return new Student("zhangsan","23");
    }
}

测试类:

public class Hell {

    public static void main(String[] args) {

        // 通过注解的方式获取spring容器,而不用xml
        ApplicationContext context = new AnnotationConfigApplicationContext(HellConfig.class);
        // 从spring容器中获取对象
        Student bean = context.getBean(Student.class);
        bean.study();
    }
}

你可能感兴趣的:(Spring)