3、Spring配置类

从spring3.0开始,@Configuration用于定义配置类,用于取代xml文件,可以进行全注解开发

@Configuration类似xml中的<beans>标签

@bean类似xml中的<bean>标签

这个博客我们使用配置来自定义bean

1、创建Student类

package com.how2j.pojo;

public class Student {
    private int age;
    private String name;

    public Student(){

    }

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

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

2、在配置类中,定义Student类的bean

package com.how2j.pojo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration  //可以将这个理解成xml中的<beans>
//使用配置类扫描批量注册,只能注册加了(@Repository,@Service, @Controller, @Componet类)
@ComponentScan(basePackages = "com.how2j.pojo")

public class SpringConfig {

    @Bean("student")
    public Student getStudent(){
        return new Student(12, "张三");
    }
}

3、测试

package test;

import com.how2j.pojo.Category;
import com.how2j.pojo.Product;
import com.how2j.pojo.SpringConfig;
import com.how2j.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestSpring {

    @Test
    //spring的控制翻转
    public void test1(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        //这里的c是在定义Category类中
        Category c = (Category) context.getBean("c");

        System.out.println(c);
    }

    @Test
    //测试spring的属性注入
    public void test2(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        //这里的p是定义在类里的, 即@Component("p")
        Product p = (Product) context.getBean("p");

        System.out.println(p);
    }

    @Test
    public void test3(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        Student stu = (Student) context.getBean("student");
        System.out.println(stu);
    }
}

Guess you like

Origin blog.csdn.net/stay_zezo/article/details/120941449