您现在的位置是:首页 > 个人日记个人日记

spring-04-对象注入

2019-02-03 18:06:11【个人日记】287人已围观

简介对象注入的方法

对象注入

一个对象

  1. package com.spring.service;
  2. public class MessageService {
  3. public void deleteById(Long id) {
  4. System.out.println("已删除id=" + id + "的信息");
  5. }
  6. }

在另一个方法中调用该对象

  1. package com.spring.controller;
  2. import com.spring.service.MessageService;
  3. public class MessageController {
  4. private MessageService messageService;
  5. public void setMessageService(MessageService messageService) {
  6. this.messageService = messageService;
  7. }
  8. public void doGet(Long id) {
  9. messageService.deleteById(id);
  10. }
  11. }

spring-config.xml中这样配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <!--服务层-->
  6. <bean id="messageService" class="com.spring.service.MessageService"></bean>
  7. <!--控制层-->
  8. <bean id="messageController" class="com.spring.controller.MessageController">
  9. <!--使用set方式注入-->
  10. <property name="messageService" ref="messageService"></property>
  11. </bean>
  12. </beans>

name是类中字段,ref是引入的对象

在测试中这样写

  1. package com.spring.controller;
  2. import com.spring.service.MessageService;
  3. import org.junit.Test;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6. import static org.junit.Assert.*;
  7. public class MessageControllerTest {
  8. @Test
  9. public void doGet() {
  10. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
  11. MessageController messageController = applicationContext.getBean(MessageController.class);
  12. messageController.doGet(1L);
  13. }
  14. }

主要是在xml配置中已经将对象连接起来,之后直接使用就行

Tags: JavaWeb  

上一篇: 网页抓取工具

下一篇: spring-01-快速上手

评论区

    2024-04-19 16:43:52

    站长

    没有登录功能是为了方便大家留言,但留言接口现在被恶意攻击,将关闭留言接口,如有疑问,请联系我的QQ 1538933906/同微信


文章评论



给自个选个头像吧!






站点信息

  • 建站时间:   2019-01-31
  • 网站程序:   Tomcat+nginx
  • 文章统计:   44篇文章
  • 标签管理:   标签云
  • 微信公众号:  扫描二维码,联系我