javascript
Spring 提供哪些配置形式?
Spring 對(duì)Java 配置的支持是由@Configuration 注解和@Bean 注解來(lái)實(shí)現(xiàn)的。由@Bean 注解的方法將會(huì)實(shí)例化、配置和初始化一個(gè)新對(duì)象,這個(gè)對(duì)象將由Spring 的IOC 容器來(lái)管理。@Bean 聲明所起到的作用與元素類似。被@Configuration 所注解的類則表示這個(gè)類的主要目的是作為bean 定義的資源。被@Configuration 聲明的類可以通過(guò)在同一個(gè)類的內(nèi)部調(diào)用@bean 方法來(lái)設(shè)置嵌入bean 的依賴關(guān)系。
最簡(jiǎn)單的@Configuration 聲明類請(qǐng)參考下面的代碼:
@Configuration public class AppConfig{@Beanpublic MyService myService() {return new MyServiceImpl();} }對(duì)于上面的@Beans 配置文件相同的XML 配置文件如下:
<beans><bean id="myService" class="com.leon.services.MyServiceImpl"/> </beans>上述配置方式的實(shí)例化方式如下:利用AnnotationConfigApplicationContext 類進(jìn)行實(shí)例化
public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);MyService myService = ctx.getBean(MyService.class);myService.doStuff(); }要使用組件組建掃描,僅需用@Configuration 進(jìn)行注解即可:
@Configuration @ComponentScan(basePackages = "com.leon") public class AppConfig { }在上面的例子中,com.gupaoedu 包首先會(huì)被掃到,然后再容器內(nèi)查找被@Component 聲明的類,找到后將這些類按照Spring bean 定義進(jìn)行注冊(cè)。
如果你要在你的web 應(yīng)用開(kāi)發(fā)中選用上述的配置的方式的話, 需要用AnnotationConfigWebApplicationContext 類來(lái)讀取配置文件,可以用來(lái)配置Spring 的Servlet 監(jiān)聽(tīng)器ContrextLoaderListener 或者Spring MVC 的DispatcherServlet。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1"><display-name>Web Application</display-name><!-- loading spring context start --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:application-web.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- loading spring context end --><!-- springmvc config start --><servlet><servlet-name>dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextClass</param-name><param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value></init-param><load-on-startup>1</load-on-startup><async-supported>true</async-supported></servlet><servlet-mapping><servlet-name>dispatcher</servlet-name><url-pattern>/*</url-pattern></servlet-mapping><!-- springmvc config end --></web-app>?
總結(jié)
以上是生活随笔為你收集整理的Spring 提供哪些配置形式?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何使用XML 配置的方式配置Sprin
- 下一篇: 怎样用注解的方式配置Spring?