1、Mapper(接口)
数据访问层->与数据库交互
Service要访问数据库时,调用Mapper接口的方法,Mapper接口使用直接在方法上写注解或Mapper配置文件中的SQL语句
1.方法上写注解@Select("select * from person where no = #{no}")
2.mapper.xml配置文件
<select id="selectMultiParam" resultType="domain.Student">
select SNO,SNAME,SSEX,SDEPT from Student
where SNAME = #{name}
or SDEPT = #{dept}
</select>
2、Service(接口)&&ServiceImpl(实现类)
业务逻辑层->处理交互业务
1.先有Service接口,再在impl包中创建实体类
2.在Service类中使用,可创建mapper对象(上面加上@Autowired注解),mapper对象可以直接使用方法(注意参数名的一致性)
3、Controller(类)
接口层->接收请求并返回响应
负责处理用户请求->调用Service处理业务->将处理结果返回给前端
1.Controller类上加上@RestMapper注解,类中创建Mapper对象(上面加上@Autowired注解),mapper对象可以直接使用方法(注意参数名的一致性)
2.方法上添加@RestMapping("/findByID")注解,前端请求为8080/findByID
前端发送HTTP请求->Controller层由URL /findByID->Service方法处理业务->Controller返回前端
4、IOC容器
spring提供的容器->管理对象
在config包内使用@Bean注解注册Bean对象(类上要加上@Component注解)
1.类上使用@Configration标记注解
2.在方法名上使用@Bean,返回类型为实体类,默认对象名为方法名;也可以自定义对象名@Bean("myBean")
3.在Application类中使用context获取对象,context.getBean("myBean");
4.创建ConfigSelector类实现ImportSelector接口,实现方法,在Selector类导入配置文件,多个类都写在配置文件中(注意写全类名),一行一个
5.配置文件保存在resource中,使用IO流读取文件,一行一行的读
package com.example.springboottest.config;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CommonConfigSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
//读取配置文件中的内容
List<String> imports = new ArrayList<>();
InputStream is = CommonConfigSelector.class.getClassLoader().getResourceAsStream("common.imports");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine())!=null){
imports.add(line);
}
}catch (IOException e){
throw new RuntimeException();
}finally {
if (br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imports.toArray(new String[0]);
}
}
6.在SpringBootApplication上添加@Import({CommonConfigSelector.class})注解,导入Selector类
5.对象实体类放入pojo包中
要加上@Component注解
6、yml配置文件
person:
no: 123
name: 张三
sex: 男
age: 20
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
username: root
password: password
7、自定义组合注解
1.创建anno包,在包中创建注解类
2.先复制进两个固定注解,在将要组合的注解复制进来,此注解就可以直接使用了(类名即注解名)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import({CommonConfigSelector.class})
public @interface EnableCommonConfig {
}