您现在的位置是:首页 > 个人日记个人日记
spring-04-对象注入
2019-02-03 18:06:11【个人日记】375人已围观
简介对象注入的方法
对象注入
一个对象
package com.spring.service;public class MessageService {public void deleteById(Long id) {System.out.println("已删除id=" + id + "的信息");}}
在另一个方法中调用该对象
package com.spring.controller;import com.spring.service.MessageService;public class MessageController {private MessageService messageService;public void setMessageService(MessageService messageService) {this.messageService = messageService;}public void doGet(Long id) {messageService.deleteById(id);}}
在spring-config.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="messageService" class="com.spring.service.MessageService"></bean><!--控制层--><bean id="messageController" class="com.spring.controller.MessageController"><!--使用set方式注入--><property name="messageService" ref="messageService"></property></bean></beans>
name是类中字段,ref是引入的对象
在测试中这样写
package com.spring.controller;import com.spring.service.MessageService;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import static org.junit.Assert.*;public class MessageControllerTest {@Testpublic void doGet() {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");MessageController messageController = applicationContext.getBean(MessageController.class);messageController.doGet(1L);}}
主要是在xml配置中已经将对象连接起来,之后直接使用就行
Tags: JavaWeb
上一篇: spring-01-快速上手
下一篇: mybatis-06-映射关系
相关文章
随机图文
评论区
2025-11-09 06:10:36
站长
没有登录功能是为了方便大家留言,但留言接口现在被恶意攻击,将关闭留言接口,如有疑问,请联系我的QQ 1538933906/同微信
