Spring Boot(5)配置篇 - @ImportResource与@Bean 加载Spring配置文件方式

使用@ImportResource 导入Spring配置文件的方式

首先我们在resources目下创建一个spring配置文件 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="helloService" class="com.lbee.service.HelloService"></bean>
</beans>

接下来创建我们的 HelloService.java

package com.lbee.service;

/**
 * @ClassName HelloService
 * @Description TODO
 * @Autchor lbee
 * @Date 2019/3/4 22:30
 * @Version 1.0
 */
public class HelloService {

    public HelloService(){
        System.out.println("hello 被加载了!");
    }

}

然后在主程序类中添加@ImportResource注解

package com.lbee;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource(value = {"classpath:beans.xml"})
public class HelloworldApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
    }

}

编写我们的单元测试,来判断一下helloService是否被spring所加载

package com.lbee;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloworldApplicationTests {

    @Autowired
    ApplicationContext ioc;

    @Test
    public void testHelloService(){
        boolean bool = ioc.containsBean("helloService");
        System.out.println(bool);
    }

}

执行结果

 

SpringBoot 推荐给容器添加组件的方式-@Bean

上面我们写了用@ImportResource注解导入spring配置文件的方式,但SpringBoot推荐我们使用更简便的全注解方式添加spring组件

首先我们创建一个配置文件类 MyAppConfig.java,也可以写在我们的主程序文件中

package com.lbee.config;

import com.lbee.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName MyAppConfig
 * @Description TODO
 * @Autchor lbee
 * @Date 2019/3/4 22:53
 * @Version 1.0
 */
@Configuration
public class MyAppConfig {

    // 将方法的返回值添加到容器中,容器中这个组件的id默认为方法名
    @Bean
    public HelloService helloService() {
        return new HelloService();
    }

}

@Configuration:指明这是一个配置文件类

delete掉我们刚才在主程序类的 代码

@ImportResource(value = {"classpath:beans.xml"})

我们再次跑一下单元测试,输出结果

OK! helloService 依然被spring加载了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值