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

SpringBoot-06-导入Spring配置

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

SpringBoot-06-导入Spring配置

导入Spring配置

默认情况下,Spring Boot 中是不包含任何的 Spring 配置文件的,即使我们手动添加 Spring 配置文件到项目中,也不会被识别。那么 Spring Boot 项目中真的就无法导入 Spring 配置吗?答案是否定的。

SpringBoot给我们提供了两种导入Spring配置的方式:

使用@importResource注解加载Spring配置

使用全注解的方式加载Spring配置

@importResource

在主启动类使用@importResource注解可以导入一个或多个Spring配置文件,并将其中的内容生效

实现

    在项目中com.liang.service创建personService的接口,代码如下:
public interface PersonService {
    public Person getPerson();
}

    在项目中com.liang.service创建personService的实现类personServiceImpl,代码如下:
public class PersonServiceImpl implements PersonService{

    @Autowired
    private Person person;
    @Override
    public Person getPerson() {
        return  person;
    }
}

3.在项目中resources下创建application.xml,代码如下:



    

    测试单元代码
    //自动装配
    @Autowired
    private Person person;

    //IOC容器
    @Autowired
    ApplicationContext ioc;

    @Test
    public void testHelloService(){
        //校验IOC容器中是否包含组件personService
        boolean flag= ioc.containsBean("personService");
        if(flag){
            System.out.println("personService已经在容器中");
        }else{
            System.out.println("personService不在容器中");
        }
    }
    @Test
    void contextLoads() {
        System.out.println(person);;
    }

    运行
    发现没有达到预想要求,而且实现类识别不了person

    主启动程序类

添加以下注解:

		@importResource(locations = 		{"classpath:/beans.xml"})
    再次执行代码

全注解方式

Spring Boot 推荐我们使用全注解的方式加载 Spring 配置,其实现方式如下:

    使用 @Configuration 注解定义配置类,替换 Spring 的配置文件;配置类内部可以包含有一个或多个被 @Bean 注解的方法,这些方法会被 AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext 类扫描,构建 bean 定义(相当于 Spring 配置文件中的标签),方法的返回值会以组件的形式添加到容器中,组件的 id 就是方法名。

代码部分

import com.liang.service.PersonService;
import com.liang.service.PersonServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyAppConfig {
    
    @Bean
    public PersonService personService() {
        System.out.println("在容器中添加了一个组件:peronService");
        return new PersonServiceImpl();
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/763780.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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