目录
(10)RESTful 风格是一种基于 REST架构风格的 API 设计风格。
一、Spring。
(1)Spring简介。

(2)Spring快速入门。

(3)Spring配置文件。

(1)Bean标签配置。
singleton 只有一个实例,也即是单例模式,即所有的共用一个对象。
prototype访问一次创建一个实例,相当于new。

(2)Bean实例化三种方式。

(3)Bean依赖注入的两种方式。

(4)Bean依赖注入的数据类型。

(5)引入子配置文件。

(4)Spring相关API。

(5)Spring配置数据源。

(1)数据源的手动创建。

(2)Spring配置数据源。

(3)Spring抽取jdbc配置文件。

(6)Spring注解开发。
(1)Spring原始注解。

(2)Spring新注解。

@PropertySource("classpath:jdbc2.properties")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("ds") //spring会将当前方法的返回值以指定名称存储到spring容器中
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("tan");
return dataSource;
}
}
注意:注解扫描一定要在配置类那里写,不然的话是不会加载这些注解的(即不动用注解) 。
//标志该类是spring的核心配置类
@Configuration
@ComponentScan("com.itheima1")
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {
}
(7) 注解需要导入的坐标:
使用Spring注解需要导入以下坐标:
1.spring-context:提供Spring IoC和Spring容器的支持,包括@Component、@Autowired和@Value等常用注解。需要在项目中引入该坐标,以获取Spring核心机制的支持。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
2.spring-web:提供Spring MVC的支持,使得可以通过注解的方式配置控制器、请求映射和视图解析器等。需要在使用Spring MVC框架时引入该坐标。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
3.spring-boot-starter-web:Spring Boot应用程序的Web相关依赖项,包括对Spring MVC,Tomcat和Spring Boot应用程序的配置支持。如果是使用Spring Boot开发Web应用,建议使用该坐标。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
</dependency>
其中,${spring.version}和${spring.boot.version}表示使用的Spring版本号和Spring Boot版本号。
4.@Resource注解的坐标是javax.annotation:javax.annotation-api。这是因为@Resource注解不是Spring框架的注解,而是Java EE规范中定义的注解。
在Java EE 5规范中引入了@Resource注解,主要用于标注对象需要使用的资源,并由容器来注入该资源。在Spring中,也可以使用@Resource注解来实现依赖注入,但需要引入javax.annotation包的javax.annotation-api依赖。
因此,在使用@Resource注解时,除了Spring核心依赖之外,还需要引入javax.annotation-api依赖,该坐标如下:
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
(8) Bean组件与注解依赖注入的区别:
(1)在Spring中,实现bean依赖注入的方式有两种:
bean组件注入、注解注入。
(2)bean组件注入:
需要显式地为bean类编写set方法或构造函数,以便在装配时将依赖注入到bean中.
(3)注解注入:
不需要显式地编写set方法或构造函数,而是通过添加特定注解来告诉Spring IoC容器自动注入对应的依赖。
注解注入的好处是更加灵活、方便,能够提高程序的可读性和可维护性。但需要注意,注解注入在写码的过程中要注意注解的使用位置和方法,以避免出错。
(9)Spring整合junit。
@RunWith是JUnit框架中的一个注解,用于指定运行测试用例的测试运行器(Runner)。
JUnit是一种Java语言的单元测试框架,旨在为Java开发者提供一个功能强大、易于使用的测试平台。
具体来说,@RunWith注解可以理解为JUnit框架的扩展点,在测试用例执行前和执行后都可以进行一些特殊的处理,如通过Mockito库模拟测试对象、使用Spring Test框架实现集成测试等。不同的Runner具有不同的处理方式,可以根据需要选择具体的Runner。
例如,对于Spring Boot应用程序的测试,可以使用@RunWith(SpringJUnit4ClassRunner.class)注解来指定使用SpringJUnit4ClassRunner作为测试运行器,以启用Spring test框架的自动注入功能,简化测试代码的编写和维护。
需要注意的是,要使用@RunWith注解,必须先导入相应的JUnit运行器类。

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
//SpringConfiguration.class是自己写的配置类
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
// @Autowired
// private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test1() throws SQLException {
// userService.save();
System.out.println(dataSource.getConnection());
}
}
(10)RESTful 风格是一种基于 REST架构风格的 API 设计风格。
注意:使用 @RestController 注解的类主要用于 RESTful 风格的接口开发,其返回的数据类型通常为 JSON、XML 等。因此,在 @RestController 注解下,通常无法返回一个视图。
当使用 Spring MVC 实现 RESTful 风格的接口时,代码的实现将符合 REST 的设计原则和规范。以下是一个简单的示例:
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUserById(@PathVariable("id") Long id) {
return userService.getUserById(id);
}
@PostMapping("/")
public ResponseEntity<?> addUser(@RequestBody User user) {
Long id = userService.addUser(user);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri();
return ResponseEntity.created(location).build();
}
@PutMapping("/{id}")
public void updateUser(@PathVariable("id") Long id, @RequestBody User user) {
userService.updateUser(id, user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable("id") Long id) {
userService.deleteUser(id);
}
}
在上述代码中,我们使用 @RestController 和 @RequestMapping 注解创建了一个 RESTful 风格的控制器。定义了四个接口分别用于获取、新增、更新和删除用户信息。
使用 RESTful 风格,我们可以通过 GET 方法请求 "/users/{id}" 来获取指定 id 的用户信息,使用 POST 方法请求 "/users/" 来新增用户信息,使用 PUT 方法请求 "/users/{id}" 来更新指定 id 的用户信息,使用 DELETE 方法请求 "/users/{id}" 来删除指定 id 的用户信息。
如果我们不使用 RESTful 风格,则可能需要为每个请求类型定义不同的 URL 来表示相同的操作,例如使用 "/users/findUserById"、"/users/addUser" 等不同的 URL 来表示用户的操作,不仅不符合 RESTful 的设计原则,而且显得繁琐和不直观。
二、Spring与Web环境集成。

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
//@WebListener
public class ContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
//读取web.xml中的全局参数
ServletContext servletContext = sce.getServletContext();
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
//spring容器创建
ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
//将spring的应用上下文对象存储到servletcontext域中
servletContext.setAttribute("app",app);
System.out.println("spring容器创建完毕!");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContextListener.super.contextDestroyed(sce);
}
}
public class WebApplicationContextUtils{
public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
return (ApplicationContext)servletContext.getAttribute("app");
}
}
//@WebServlet("/quick")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//WebApplicationContextUtils.getWebApplicationContext这里的是官方api的,并非自己写的,但是跟自己写的差不多一个原理
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
UserService userService = app.getBean(UserService.class);
userService.save();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
注:根据需要的不同的监听器可以通过继承不同的监听器类。
362

被折叠的 条评论
为什么被折叠?



