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);
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

圣诞节不感冒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值