目錄java
最近才體會到Spring註解配置的遍歷,總結一下。web
@Configuration @EnableWebMvc @ComponentScan("cn.fjhdtp.maventest.controller") public class SpringMvcConfig { @Bean public InternalResourceViewResolver internalResourceViewResolver() { InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver(); internalResourceViewResolver.setViewClass(JstlView.class); internalResourceViewResolver.setPrefix("/WEB-INF/views/"); internalResourceViewResolver.setSuffix(".jsp"); return internalResourceViewResolver; } }
@Configuration
代表這是一個配置類;@EnableWebMvc
啓用SpringMVC。redis
public class WebInitializer implements WebApplicationInitializer{ public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(SpringMvcConfig.class); ctx.setServletContext(servletContext); ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.addMapping("/"); servlet.setLoadOnStartup(1); } }
實現__WebApplicationInitializer__的類的__onStartup__方法會在Spring啓動以後被執行,而且這個優先級在listener以前。能夠用@Order(100)
註解來配置執行的順序,沒有這個註解則表明是最早執行。spring
相似<context:component-scan />
。mvc
@ComponentScan(value = "cn.fjhdtp.maventest", excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Configuration.class, Controller.class}), })
與@Configuration
結合使用,讀取properties文件app
@PropertySources({ @PropertySource(value = "classpath:jedis.properties") })
與@PropertySource
或者<context:property-placeholder/>
結合使用,注入屬性值。jsp
@Value("${redis.hostName:127.0.0.1}") private String hostName; // 主機名 @Value("${redis.port:6379}") private int port; // 監聽端口 @Value("${redis.auth:}") private String password; // 密碼 @Value("${redis.timeout:2000}") private int timeout; // 客戶端鏈接時的超時時間(單位爲秒)
@Controller
代表這個類是一個controller,和@RequestMapping
結合來配置映射的路徑。maven
@Component
代表這是一個Bean,可是若是知道屬於那一層最好仍是用@Service
或者@Repository
。spa
用在Service層。code
用在Dao層。