理解@ComponentScan注解

spring mvc当中经常可以看到@ComponentScan这个注解,

那么怎么样去理解它呢?

1.配置视图控制器

  1. package com.apress.prospringmvc.bookstore.web.config;  
  2. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;  
  3. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;  
  4.   
  5. @Configuration  
  6. @EnableWebMvc  
  7. @ComponentScan(basePackages = { “com.apress.prospringmvc.bookstore.web” })  
  8. public class WebMvcContextConfiguration extends WebMvcConfigurerAdapter {  
  9.   
  10.     @Override  
  11.     public void addViewControllers(final ViewControllerRegistry registry) {  
  12.         registry.addViewController(”/index.htm”).setViewName(“index”);  
  13.     }  
  14. }  
package com.apress.prospringmvc.bookstore.web.config; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc @ComponentScan(basePackages = { “com.apress.prospringmvc.bookstore.web” }) public class WebMvcContextConfiguration extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { registry.addViewController(“/index.htm”).setViewName(“index”); } }

2.基于注解的Controller

  1. package com.apress.prospringmvc.bookstore.web;      
  2. import org.springframework.stereotype.Controller;      
  3. import org.springframework.web.bind.annotation.RequestMapping;      
  4. import org.springframework.web.servlet.ModelAndView;      
  5. @Controller      
  6. public class IndexController {      
  7. @RequestMapping(value = “/index.htm”)      
  8.     public ModelAndView indexPage() {       
  9.         return new ModelAndView(“index”);      
  10.     }      
  11. }     
package com.apress.prospringmvc.bookstore.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class IndexController { @RequestMapping(value = “/index.htm”) public ModelAndView indexPage() { return new ModelAndView(“index”); } }

那么对于配置的视图控制器加了

@Configuration 和@ComponentScan注解背后会做什么呢?


其实很简单,@ComponentScan告诉Spring 哪个packages 的用注解标识的类 会被spring自动扫描并且装入bean容器。

例如,如果你有个类用@Controller注解标识了,那么,如果不加上@ComponentScan,自动扫描该controller,那么该Controller就不会被spring扫描到,更不会装入spring容器中,因此你配置的这个Controller也没有意义。

类上的注解@Configuration 是最新的用注解配置spring,也就是说这是个配置文件,和原来xml配置是等效的,只不过现在用Java代码进行配置了 加上一个@Configuration注解就行了,是不是很方便,不需要那么繁琐的xml配置了,这样基于注解的配置,可读性也大大增高了。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值