前言
简单spring注解搭建使用,使用工具:IDEA2020,采用了maven
一、pom.xml添加依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
</dependencies>
二、bean.xml配置文件
在resources下创建bean.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
// 开启spring注解扫描
<context:annotation-config/>
<context:component-scan base-package="yanyu"></context:component-scan>
</beans>
向上面的xml.的约束在spring官网上查询的:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core
xmlns:context是注解需要用到的
如果你想使用aop(切面)也需要在官网上找它的约束才可以在xml使用哟!
三、搭建工程,我们一般采用三级架构
每一层,我们都需要添加相应的注解:
比如:servier层:我们加@Service(“accountService”)
持久层:我们加@Repository(“accountDao”)
补充:
括号里的名称是可以自己定义的。如果没有写:其默认是和该层的类名是一样,开头改小写而已,使用时注意就好。
比如:@Repository("accountDaoImpl") public class AccountDaoImpl implements IAccountDao {
这个时候,括号里的也是可以省略不写的。
四、其余的实现类,接口的看个人想法写
这里就不啰嗦了
五、在main类里
记得添加:然后去使用bean去遛对象,实现方法
// 获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 根据id获取Bean对象
IAccountService as =(IAccountService)ac.getBean("accountService");
//IAccountService是一个接口名
as.方法();
```