package com.example.testproject.service;
public interface Calculate {
static Calculate newInStance() {
return new CalculateSum();
}
int calculate(int a, int b);
}
package com.example.testproject.service;
//包可见性,不对外暴露,只能通过interface调用
class CalculateSum implements Calculate {
@Override
public int calculate(int a, int b) {
return a+b;
}
}
package com.example.testproject.controller;
import com.example.testproject.service.Calculate;
import lombok.Getter;
import lombok.Setter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("simple")
public class SimpleController {
@Getter
@Setter
static class RequestParams {
private int a;
private int b;
}
@GetMapping("calculate")
public int calculateSum(RequestParams params) {
Calculate calculate = Calculate.newInStance();
return calculate.calculate(params.getA(), params.getB());
}
}
在实现接口时,不需要用@Service或者@Componment注入,对外只暴露interface,接口实现不对外暴露,只能通过接口访问。