SpringBoot中如何进行Bean配置

 时间:2024-10-12 02:29:09

1、Bean配置。在使用Spring进行开发配置的时候有两类配置:*.xml配置文件、配置的Bean(@Configure),于是在SpringBoot的开发的时间里面,为了继续崇尚所谓的“零配置”,提供有一种简单的支持,也就是说如果现在你真的有配置需要通过*.xml文件编写,但是又不想出现配置文件的话,这个时候最简单的做法就是使用Bean的方式进行类的配置。前提:该配置程序的Bean所在的包必须是程序启动类所在包的子包之中,这样才可以自动扫描到。

2、下面准备一个不是很正规的程序,建立一个业务接口,而后定义这个接口的子类:package com.gwolf.service;public interface IMessageService { public String info();}

SpringBoot中如何进行Bean配置

4、在控制器MessageController中注入IMessageService:package co罪焐芡拂m.gwolf.controller;import ch.qos.logback.core.net.SyslogOutputStream;import com.gwolf.service.IMessageService;import com.gwolf.util.controller.AbstractBaseController;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@RestControllerpublic class MessageController extends AbstractBaseController{ @Resource private IMessageService messageService; @RequestMapping(value="/", method = RequestMethod.GET) public String idnex() { return this.messageService.info(); } @RequestMapping(value="/echo", method = RequestMethod.GET) public String echo(String mid) { System.out.println("访问:" + super.getMessage("member.add.action")); return super.getMessage("welcome.msg",mid); }}

SpringBoot中如何进行Bean配置

6、下面利用以上的程序来了解一下什么叫做Bean配置,为了清楚的发现Bean的特点删除掉业务实现子类中的“@Service”注解,也就是说这个对象现在无法直接注入,于是下面在启动类所在包的子包里面建立一个配置程序类:com.gwolf.config.ServiceConfig。package com.gwolf.config;import com.gwolf.service.IMessageService;import com.gwolf.service.impl.MessgeServiceImpl;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration //此处为配置项public class ServiceConfig { @Bean //此处返回的是一个Spring的配置Bean,与xml的<bean>等价 public IMessageService getMessageService() {//方法名称随便写 return new MessgeServiceImpl(); }}

SpringBoot中如何进行Bean配置

8、此时采用了自动扫描Bean的模式来进行相关对象的配置。SSM或SSH开发框架出现的时间比较长,现在迁移到SpringBoot之中,那么说如果你现在已经有一个非常完善的xml配置文件出现了,那么难道还需要将整个的xml配置文件转化为Bean配置吗?为了防止这类情况出现,SpringBoot也支持有配置文件的读取。这样就完成了SpringBoot中如何进行Bean配置。

  • jsp页面如何查看列表列表
  • ppt如何删除选择显示悬浮工具栏
  • 膳食房膳食纤维为什么可以降血脂、预防冠心病?
  • 资源部署及交付流程概述
  • 有哪些免费实现网站评论的第三方评论系统插件
  • 热门搜索
    上海青青旅游世界 暑假旅游好去处 春节去哪旅游好 杭州附近的旅游景点 墨江旅游 广州校内旅游网 山西大同旅游景点大全 畅游天下旅游同行网 上川岛旅游 上海到乌镇旅游攻略