栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

3、spring配置类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

3、spring配置类

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

@Configuration类似xml中的标签

@bean类似xml中的标签

这个博客我们使用配置来自定义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中的
//使用配置类扫描批量注册,只能注册加了(@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);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/346450.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号