1.Spring-IOC框架快速入门
- Spring配置文件之分模块开发
在主配置文件中引入其他配置文件
1
<import resource="配置文件名"/>
- Spring依赖注入
数据库配置和Bean的解耦
1
2
3
4
5<!--jdbc.properties-->
driver=com.mysql.cj.jdbc.Driver
path=jdbc:mysql://localhost:3306/share
user=root
pwd=1234561
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20<!--applicationContext.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--Spring容器加载外部数据库配置文件-->
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<!--变量名不能和name属性保持一致!!!!!!-->
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${path}"/>
<property name="username" value="${user}"/>
<property name="password" value="${pwd}"/>
</bean>
<bean id="user" class="domain.user"/>
</beans>
- Spring注解注入
注解(Spring的原始注解,主要替代<Bean>配置) | 说明 |
---|---|
@Conpontent | 使用在类上用于实例化Bean |
@Controller | 使用在web层类上用于实例化Bean |
@Service | 使用在service层类上用于实例化Bean |
@Repository | 使用在dao层用于实例化Bean |
@Autowired | 是用在字段上用于根据类型注入 |
@Qualifier | 结合**@Autowired一起使用用于根据名称**进行依赖注入 |
@Resource(name=”实例化Bean的值”) | 相当于**@Autowired+@Qualifier**,按照名称进行注入 |
@Value | 注入普通属性 |
@Scope | 标定Bean的作用范围 |
@PostConstruct | 使用在方法上标注该方法为Bean的初始化方法 |
@PreDestroy | 使用在方法上标注该方法是Bean的销毁方法 |
Spring的新注解 | |
@Configuration | 指定当前类是一个配置类 |
@ComponentScan(“包路径”) | 相当于xml的**<context:component-scan base-package=””/>—用于spring在创建容器时要扫描**的包 |
@Bean | 用于把当前方法的返回值作为bean对象存入spring的ioc容器中 |
@Import(文件名.class) | 导入其他配置文件 |
@PropertySource(”classpath:配置文件名”) | 用于指定properties文件的配置 |
@value | 用于属性注入 |
Spring-test(Spring集成test) | |
@Runwith(SpringJunit4ClassRunner.class) | 使用@Runwith注解替换原来的运行期 |
@ContextConfiguration(classes=”配置类.class”/“classpath:xml配置文件”) | 指定配置文件或配置类 |
使用@Autowired注入需要测试的对象,创建测试方法进行测试 |
- Spring 集成 Junit
- 导入spring集成的Junit的坐标
- 使用@Runwith注解替换原来的运行期
- 使用@ContextConfiguration指定配置文件或配置类
- 使用@Autowired注入需要测试的对象
- 创建测试方法进行测试


- Spring 集成 web
- 在web.xml中配置ContentLoderListener监听器(导入spring-web坐标)
- 在WebApplicationContextUtils获得应用上下文对象ApplicationContext



本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Jilfoyle!