零、本文纲要
- 一、Spring基础
- 相关依赖
- xml文件开发
- 半注解开发
- 纯注解开发
一、Spring基础
1. 相关依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
2. xml文件开发
- ① <bean>标签
管理配置bean
<bean id="" class="" scope="" init-method="" destroy-method=""/>
- ② <context>标签
Ⅰ 加载配置文件
<context:property-placeholder location="jdbc.properties"/>
Ⅱ 引入配置文件的值
然后使用${key}进行属性注入
3. 半注解开发
- ①
@Component
注解
@Controller@Service@Repository
增强可读性
- ② 配置注解扫描
<context:component-scan base-package="com.stone"/>
4. 纯注解开发
无需配置applicationContext.xml
配置文件
- ① 配置类
@Configuration
public class SpringConfig {
}
- ② 添加注解扫描
使用@ComponentScan注解,进行注解扫描
@Configuration
@ComponentScan("com.stone")
public class SpringConfig {
}
- ③ Bean的生命周期注解
在对应的方法上添加@PostConstruct
和@PreDestroy
注解即可
@Repository
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
@PostConstruct //在构造方法之后执行,替换 init-method
public void init() {
System.out.println("init ...");
}
@PreDestroy //在销毁方法之前执行,替换 destroy-method
public void destroy() {
System.out.println("destroy ...");
}
}
<bean id="" class="" scope="" init-method="" destroy-method=""/>
分别对应@Component、@Scope、@PostConstruct、@PreDestroy注解
- ④ 依赖注入
类型注入添加@Autowired
注解
一般类型注入添加@Value
注解
- ⑤ 读取properties配置文件
Ⅰ 使用@PropertySource注解读取配置文件
@Configuration
@ComponentScan("com.stone")
@PropertySource("jdbc.properties")
public class SpringConfig {
}
Ⅱ 使用@Value
@Value("${jdbc.driver}")
private String driver;
- ⑥ 第三方Bean
使用@Bean注解
@Configuration
public class JdbcConfig {
@Bean
public DataSource dataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/spring_db");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
}
注意:不能使用DataSource ds = new DruidDataSource()
,DataSource接口没有Set属性的方法
- ⑦ 引入外部配置
Ⅰ 使用@ComponentScan注解引入
@Configuration
@ComponentScan("com.stone.config")
public class SpringConfig {
}
Ⅱ 使用@Import注解引入
@Configuration
//@ComponentScan("com.stone.config")
@Import({JdbcConfig.class})
public class SpringConfig {
}
二、结尾
以上即为Spring基础使用的全部内容,感谢阅读。
网友评论