SpringBoot学习5之springboot的全局配置

springboot配置方式

第一步:再com.pp.springboothelloworld中创建service包,然后创建HttpService类

package com.pp.springboothelloworld.service;

public class HelloService {
}

第二步:再com.pp.springboothelloworld中创建config包,然后创建Myconfig类

package com.pp.springboothelloworld.config;

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

@Configuration
public class Myconfig {
    @Bean
    public HelloService helloService(){
        System.out.println("@bean给容器添加组件");
        return new HelloService();
    }
}

在Myconfig类中使用@Configuration注解,然后再定义一个返回类型为HelloService 的helloService()方法,并且用@Bean注解,返回是返回一个new HelloService()

第三步:再测试类中写测试方法

	 @Autowired
    ApplicationContext ioc;
    @Test
    public void hello(){
        boolean helloService = ioc.containsBean("helloService");
        System.out.println(helloService);
    }

测试方法中,测试方法外对ApplicationContext ioc使用了 @Autowired注解。方法里面调用了ioc.containsBean(“helloService”),这里用来寻找Myconfig类中helloService()方法.如果Myconfig中没有该方法就返回false,如果找到该方法就执行并且返回true.

第四步:测试

在这里插入图片描述
如图所示,测试方法中成功找到Myconfig类中的helloService方法,并且还执行方法里面的内容,最终返回一个true.相反我们运行一个Myconfig没有的方法,就会返回false。

spring配置方式

第一步:再resource创建beans.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.pp.springboothelloworld.service.HelloService"/>
</beans>

这里的中id使用service类中的小写,class写com.pp.springboothelloworld.service.HelloService。

第二步:在主配置类SpringBootHelloworldApplication中使用注解@ImportResource(locations = “classpath:beans.xml”)用来读取上面一步beans.xml的内容

第三步:在HelloService ,下写一个sava()方法,模拟数据库的保存

package com.pp.springboothelloworld.service;

public class HelloService {
    public void save(){
        System.out.println("保存");
    }
}

第四步:在测试类中重新定义一个测试方法

hello1()

 @Test
    public void hello1(){
        HelloService bean =(HelloService) ioc.getBean("helloService");

    }

第五步:测试结果

在这里插入图片描述

源码地址:https://gitee.com/yangforever/project-learning/tree/master/demo/SpringBoot/spring-boot-helloworld2

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值