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

@Configuration和@Bean注解的使用

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

@Configuration和@Bean注解的使用

开始前,在maven中导入spring-context依赖

@Configuration使用:加在类的上方,表示当前类是作为配置文件使用的,就是用来配置容器的。
                相当于Spring的配置文件beans.xml

为了进行测试,先创建一个Student类

package org.example.vo;

public class Student {
    private String name;
    private Integer age;
    private String sex;

    //getter setter

    //toString
}

创建一个SpringConfig类,在类名上方加上@Configuration,并在类中写入方法

@Configuration
public class SpringConfig {
    
    @Bean
    public Student createStudent(){
        Student s1=new Student();
        s1.setAge(16);
        s1.setName("zs");
        s1.setSex("男");
        return s1;
    }
}

进行测试:

    @Test
    public void test02(){
        ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfig.class);

        //若没有指定属性名,则默认为方法名
        Student student=(Student)ac.getBean("createStudent");
        System.out.println(student);
    }

结果:

 

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

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

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