xml配置文件文件
如果用了xml方式获取了ctx,然后又是用的注解,需要在xml里面增加扫描,扫描对应包下面的注解
<context:component-scan base-package="com.example.Annotion"></context:component-scan>
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserService userService = (UserService) ctx.getBean("userService");
userService.saveUser();
注解,如果用下面的方式获取ctx,不需要去配置扫描了
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext("com.example.Annotion");
UserService bean = ctx.getBean(UserServiceImpl.class);
bean.saveUser();
@Autowired
@Qualifier("userDao")
===
@Resource("userDao")
相等的
autowired+Qualifier = resource
加载配置文件
<context:property-placeholder location="classpath:conn.properties"/><!-- 加载配置文件 -->
<!-- com.mchange.v2.c3p0.ComboPooledDataSource类在c3p0-0.9.5.1.jar包的com.mchange.v2.c3p0包中 -->
<bean id="dataSource" class="${dataSource}"> <!-- 这些配置Spring在启动时会去conn.properties中找 -->
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${jdbcUrl}" />
<property name="user" value="${user}" />
<property name="password" value="${password}" />
</bean>
集成web
- 首先导入坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.16.RELEASE</version>
</dependency>
- 在web.xml中配置监听器, 当监听到servletContext创建的时候就会去加载配置文件.相当于应用一启动就加载了
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
- 通过WebApplicationContextUtils(spring封装的工具类)来获取WebApplicationContext ,为applicationContext的子类
ServletContext servletContext = request.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
网友评论