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

@configuration和@bean注解

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

@configuration和@bean注解

spring注解目录

sping注解包括了许多的spring相关注解的解释和应用。


目录

概述

注解方式

调用方式


概述

@configuration和@bean注解的含义和使用方式。

当然这之前需要在pom.xml中引入,springcontext。

注解方式

@configuration

主要是告诉spring,我是配置类,下面能配置很多东西。

@bean

主要是写在@configuration下面的,声明了下面能配置很多东西,@bean就说,我要配置一个容器,里面装一个人的名字和年龄。

package config;


import bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration//告诉spring这是一个配置类
public class MainConfig {
    //给容器注册一个Bean
    @Bean("person02")
    public Person person(){

        return new Person("李四","20");
    }
}

 person类的声明

package bean;

public class Person {
    private String name;
    private String 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;
    }

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

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

    public Person() {
        super();
    }
}

调用方式

怎么调用获取容器中的值,我们需要new一个AnnotationConfigApplicationContext对象,这个对象负责调用,注册容器的地址。

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);

这下拿到,容器中的值了

 然后我不仅想要拿到值,我还要拿到容器,调用容器的值,肯定就要找到这个容器,这时候通过getBeanNamesForType这个方法,就能拿到容器的id,也就是他的名字person。

 容器id默认是方法名。可以给他改名字吗?在@bean("我改名字了person02"),这样就完成了改名。

 最后附上测试类的全代码。

package test;

import bean.Person;
import config.MainConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainTest {
    public static void main(String[] args) {

        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);

        String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
        for(String name: namesForType){
            System.out.println(name);
        }

    }
}

 

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

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

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