@Service注解,业务层
@Service的作用相当于在配置文件中配置<bean id = "xxx" ></bean>
Spring2.5引入组件自动扫描机制,可以再累路径下,扫描标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入spring容器中管理,注解的作用相当于在xml文件中使用bean节点配置组件。使用自动扫描机智,需要配置:<context:component-scan base-package="com.xxx....">,其中,base-package为需要扫描的包(包含所有子包)。
在Service类上添加@Service注解,在Controller类中在相应的service对象上添加@Autowired注解,会自动扫描并注入。
@Controller
@RequestMapping("/test/")
public class TestController{
@Autowired
private TestService testService;
@RequestMapping("test-service")
public Response<String> test(@RequestBody data){
...
testService.test();
...
}
}
@Service
public class TestService{
public void test(){
System.out.println("TestService test");
}
}
参考博客:https://blog.youkuaiyun.com/xiao190128/article/details/54890759
本文介绍了Spring框架中自动扫描机制的基本用法,包括如何使用@Service注解将业务层类纳入Spring容器管理,以及如何通过@Autowired实现不同组件间的依赖注入。示例展示了控制器和服务层的具体配置方式。
844

被折叠的 条评论
为什么被折叠?



