实用Spring教程(2)----注入组件

在上一课的基础上,java文件目录改为如下形式

java

    |- com

        |- byron

            |- spring

                |- demo

                Application.java

                |- controller

                    HelloController.java

                |- service

                    SomeServiceI.java

                    |- impl

                        SomeServiceImpl



HelloController.java

package com.byron.spring.demo.controller;

import com.byron.spring.demo.service.SomeServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping
public class HelloController {

    // 把业务处理类,注入到引用中
    @Autowired
    SomeServiceI someService;

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(@RequestParam(name = "name", defaultValue = "spring", required = false) String name){

        return someService.doSomething(name);
    }

}

SomeServiceI.java

package com.byron.spring.demo.service;

public interface SomeServiceI {

    /**
     * 模拟一个业务方法
     * @param name
     * @return
     */
    String doSomething(String name);

}

SomeServiceImpl.java

package com.byron.spring.demo.service.impl;

import com.byron.spring.demo.service.SomeServiceI;
import org.springframework.stereotype.Service;

@Service
public class SomeServiceImpl implements SomeServiceI {

    @Override
    public String doSomething(String name) {
        try {
            // 模拟业务处理消耗了时间
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return name + " has finsished";
    }
}

运行下main方法,访问 http://localhost:8080/hello,等待一秒后就会出现

spring has finsished


课后作业

1、请同学们自行了解

@Service 和 @Component的作用和区别

@Autowired的作用


猜你喜欢

转载自blog.csdn.net/dwdyoung/article/details/80860676