@Configuration配置类

@Configuration

从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

xml版

  1. 编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String name;
    private Integer age;
}
  1. 配置xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
	http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="Person" class="cn.jbit.bean.Person">
        <property name="age" value="18"></property>
        <property name="name" value="zhangsan"></property>
    </bean>

</beans>
  1. 测试
@Test
    public void test01(){
        ClassPathXmlApplicationContext cpx = new ClassPathXmlApplicationContext("beans.xml");
        Person bean = cpx.getBean("Person",Person.class);
        System.out.println(bean);
    }

在这里插入图片描述

注解版

  1. 编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String name;
    private Integer age;
}
  1. 编写测试类
//配置类 == 配置文件
@Configuration   //告诉spring这是一个配置类
public class MainConfig {
//    给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
    @Bean("PS")   //给id起别名
    public Person person(){
        return new Person("lisi",20);
    }
}
  1. 测试
    @Test
    public void test02(){
       ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);
        Person bean = app.getBean(Person.class);
        System.out.println(bean);
//        获取bean的id名字
        String[] beanNamesForType = app.getBeanNamesForType(Person.class);
        for (String name : beanNamesForType) {
            System.out.println(name);
        }
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值