Spring配置类and配置文件(@Configuration和@Bean注解)

加入依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.22</version>
        </dependency>
    </dependencies>

创建一个实体类Person

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
    private String name;
    private String age;
}

第一种:用xml配置文件的方式
创建一个spring xml的文件命名为bean.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.xsd">

    <bean id="person" class="com.spring.bean.Person">
        <property name="age" value="20"></property>
        <property name="name" value="小杨"></property>
    </bean>
</beans>

在main方法中进行测ing

 public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //可以是id,也可以是类的class对象
        //Object person =  context.getBean("person");
        Person person =  context.getBean(Person.class);
        System.out.println(person);

控制台输出:
在这里插入图片描述
第二种:配置类的方式
创建一个配置类

@Configuration //告诉spring这是个配置类
public class SpringConfig {

    /**
     * 给spring ioc中注册一个bean,返回值即为类型,方法名即为id
     * 将方法返回值注入到容器中
     */
    @Bean(value = "per") //也可定义别名id,不加value值则默认方法名为id
    public Person personTest(){
        return new Person("小陈","22");
    }
}

main方法测试

 ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
//        Object person = context.getBean("personTest");
        Person person = context.getBean(Person.class);
        System.out.println(person);

        //获取id
        String[] beanNamesForType = context.getBeanNamesForType(Person.class);
        for (String bean: beanNamesForType){
            System.out.println(bean);
        }
    }

控制台输出:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值