Spring笔记
初始化Spring
-
目录结构
-
mvnw mvnw.cmd: 这是Maven包装器(wrapper)脚本。借助这些脚本,即便你的机器上没有安装Maven,也可以构建项目。
-
pom.xml: 这是Maven构建规范
-
application.java: 这是springboot的启动类,它会启动项目
-
application.properties: 用来指定项目的一些配置。
-
static: 用来存放浏览器需要的一些文件(图片、样式表、JavaScript等)
-
templates:用来存放渲染的模板(Thymeleaf)
-
TacoCloudApplicationTests.java:测试类
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> #父依赖
<version>2.6.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wuan</groupId>
<artifactId>wuan</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>wuan</name>
<packaging>jar</packaging> #打包方式为jar包,也可以修改为war包 也可以修改为pom,用来聚合工程或传递依赖用
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> #打包用的插件
</plugin>
</plugins>
</build>
</project>
application.java(引导类)
@SpringBootApplication
public class WuanApplication {
public static void main(String[] args) {
SpringApplication.run(WuanApplication.class, args);
}
}
- @SpringBootApplication是一个组合注解(@SpringBootConfiguration和@EnableAutoConfiguration和@SpringBootConfiguration)
- @SpringBootConfig:将该类声明为配置类。
- @EnableAutoConfiguration:启动Springboot的自动配置。
- @ComponentScan:启用组件扫描。application.java之所以放到和别的同一目录,是因为ComponentScan会扫描当前目录以及当前目录的子目录下的@Controller、@Service这样的注解,并且生成spring应用上下文的组件。
处理web请求
@Controller
@RestController
@RequestMapping("/study")
public class StudyController {
@GetMapping("/getMapping/{id}")
public String testGetMapping(@PathVariable("id") String id){
return id;
}
@PostMapping("/postMapping")
public String testPostMapping(@RequestBody Student student){
return "index";
}
@PostMapping("/testRequestParam")
public String testRequestParam(@RequestParam("userName") String userName){
return "index";
}
}
- @Controller:作用让Spring应用上下文识别这个类并识别为组件(类似的有@Component、@Service和@Repository)
- @RestController =@ResponseBody+@Controller
- @ResponseBody:返回json字符串,如果不加的话,返回的字符串就是别的url地址。
- @RequestMapping("/study"):路由方法,默认为get路由,也可以指定如@RequestMapping(value="/add",method = RequestMethod.POST)
- @PathVariable(“id”) :根据路径来获取参数。
- @RequestBody :获取的参数为json格式
- @RequestParam:用来获取?后面的参数。
注入方式
- @Autowride:默认为按类型匹配(属于spring注解),默认情况下,需要注入的对象是必须存在的(也可以修改为@Autowired(required=false)),如果想要按名称来进行装配可以修改为@Autowride()@Qualifier(“student”)
- @Resource:默认为按名称进行匹配(注解属于J2EE的),如果按照名称找不到的话,就会按照类型来查找。但是如果指定了名字的话,就只会按照名字来查找即:@Resource (name= “baseDao”)
实体类方面的注解
@Data
@AllArgsConstructor
@NoArgsConstructor
@RequiredArgsConstructor
public class Student {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GTM+8")
String time;
@Size(min = 5,max = 10,message = "Name must be at least 5 and not more than 10 characters long ")
String name;
@NonNull
String age;
@NotBlank
String sex;
}
- @Data:生成getter、setter、tostring等方法
- @AllArgsConstructor:生成包含所有参数的构造器
- @NoArgsConstructor:生成空构造器
- @RequiredArgsConstructor:生成以final属性作为参数的构造器
- @NotNull: 定义在参数上,指定参数不为空。
- @NotBlank:定义在参数上,不仅字符串不能为空,并且内容也不能为空。
- @Size():可以规定字符串的长度
SpringData
传统的查询(不适用Jdbctemplate)
public class StudyData {
@Autowired
DataSource dataSource;
public void testData(){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet =null;
try {
connection = dataSource.getConnection();
String sql = "select id, name type from student where id = ? ";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"id");
resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
String name = resultSet.getString("name");
System.out.println(name);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
上面的代码有,创建sql语句、创建连接、关闭连接等操作。
使用Jdbctemplate进行增删改查
public class StudyData {
@Autowired
JdbcTemplate jdbcTemplate;
public void testData2(){
Student student = jdbcTemplate.queryForObject("select id, name type from student where id = ?",Student.class,"id");
System.out.println(student.getName());
}
}
上面代码是使用Jdbctemplate操作数据库的。