spring该怎么简单使用

发布时间:2022-01-05 09:16:15 作者:柒染
来源:亿速云 阅读:196

Spring该怎么简单使用

引言

Spring框架是Java开发中最流行的开源框架之一,它提供了全面的基础设施支持,帮助开发者快速构建企业级应用。Spring的核心特性包括依赖注入(DI)、面向切面编程(AOP)、事务管理、数据访问、Web开发等。本文将详细介绍如何简单使用Spring框架,帮助初学者快速上手。

1. Spring框架概述

1.1 什么是Spring

Spring是一个轻量级的Java开发框架,旨在简化企业级应用的开发。它通过提供一系列模块和工具,帮助开发者解决常见的开发问题,如依赖管理、事务管理、安全性等。

1.2 Spring的核心模块

Spring框架由多个模块组成,主要包括:

2. Spring的简单使用

2.1 环境准备

在开始使用Spring之前,需要确保开发环境已经准备好。以下是基本的环境要求:

2.2 创建Spring项目

2.2.1 使用Maven创建项目

  1. 打开命令行工具,进入项目目录。
  2. 使用以下命令创建一个Maven项目:
   mvn archetype:generate -DgroupId=com.example -DartifactId=spring-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
  1. 进入项目目录:
   cd spring-demo
  1. pom.xml中添加Spring依赖:
   <dependencies>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context</artifactId>
           <version>5.3.21</version>
       </dependency>
   </dependencies>
  1. 更新项目依赖:
   mvn clean install

2.2.2 使用Gradle创建项目

  1. 打开命令行工具,进入项目目录。
  2. 使用以下命令创建一个Gradle项目:
   gradle init --type java-application
  1. build.gradle中添加Spring依赖:
   dependencies {
       implementation 'org.springframework:spring-context:5.3.21'
   }
  1. 更新项目依赖:
   gradle build

2.3 配置Spring容器

Spring容器是Spring框架的核心,负责管理Bean的生命周期和依赖关系。Spring提供了多种配置方式,包括XML配置、注解配置和Java配置。

2.3.1 XML配置

  1. src/main/resources目录下创建applicationContext.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"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd">

       <bean id="helloWorld" class="com.example.HelloWorld">
           <property name="message" value="Hello, World!"/>
       </bean>
   </beans>
  1. 创建HelloWorld类:
   package com.example;

   public class HelloWorld {
       private String message;

       public void setMessage(String message) {
           this.message = message;
       }

       public void getMessage() {
           System.out.println("Your Message : " + message);
       }
   }
  1. 创建主类App
   package com.example;

   import org.springframework.context.ApplicationContext;
   import org.springframework.context.support.ClassPathXmlApplicationContext;

   public class App {
       public static void main(String[] args) {
           ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
           HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
           obj.getMessage();
       }
   }
  1. 运行App类,输出结果为:
   Your Message : Hello, World!

2.3.2 注解配置

  1. src/main/resources目录下创建applicationContext.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
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd">

       <context:component-scan base-package="com.example"/>
   </beans>
  1. HelloWorld类上添加@Component注解:
   package com.example;

   import org.springframework.stereotype.Component;

   @Component
   public class HelloWorld {
       private String message = "Hello, World!";

       public void getMessage() {
           System.out.println("Your Message : " + message);
       }
   }
  1. 创建主类App
   package com.example;

   import org.springframework.context.ApplicationContext;
   import org.springframework.context.support.ClassPathXmlApplicationContext;

   public class App {
       public static void main(String[] args) {
           ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
           HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
           obj.getMessage();
       }
   }
  1. 运行App类,输出结果为:
   Your Message : Hello, World!

2.3.3 Java配置

  1. 创建配置类AppConfig
   package com.example;

   import org.springframework.context.annotation.Bean;
   import org.springframework.context.annotation.Configuration;

   @Configuration
   public class AppConfig {
       @Bean
       public HelloWorld helloWorld() {
           HelloWorld helloWorld = new HelloWorld();
           helloWorld.setMessage("Hello, World!");
           return helloWorld;
       }
   }
  1. 创建主类App
   package com.example;

   import org.springframework.context.ApplicationContext;
   import org.springframework.context.annotation.AnnotationConfigApplicationContext;

   public class App {
       public static void main(String[] args) {
           ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
           HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
           obj.getMessage();
       }
   }
  1. 运行App类,输出结果为:
   Your Message : Hello, World!

2.4 依赖注入

依赖注入(Dependency Injection, DI)是Spring框架的核心特性之一,它通过将对象的依赖关系交给Spring容器管理,从而降低代码的耦合度。

2.4.1 构造器注入

  1. 创建MessageService接口:
   package com.example;

   public interface MessageService {
       String getMessage();
   }
  1. 创建MessageServiceImpl类:
   package com.example;

   public class MessageServiceImpl implements MessageService {
       @Override
       public String getMessage() {
           return "Hello, World!";
       }
   }
  1. 修改HelloWorld类:
   package com.example;

   public class HelloWorld {
       private MessageService messageService;

       public HelloWorld(MessageService messageService) {
           this.messageService = messageService;
       }

       public void getMessage() {
           System.out.println("Your Message : " + messageService.getMessage());
       }
   }
  1. 修改AppConfig类:
   package com.example;

   import org.springframework.context.annotation.Bean;
   import org.springframework.context.annotation.Configuration;

   @Configuration
   public class AppConfig {
       @Bean
       public MessageService messageService() {
           return new MessageServiceImpl();
       }

       @Bean
       public HelloWorld helloWorld(MessageService messageService) {
           return new HelloWorld(messageService);
       }
   }
  1. 运行App类,输出结果为:
   Your Message : Hello, World!

2.4.2 Setter注入

  1. 修改HelloWorld类:
   package com.example;

   public class HelloWorld {
       private MessageService messageService;

       public void setMessageService(MessageService messageService) {
           this.messageService = messageService;
       }

       public void getMessage() {
           System.out.println("Your Message : " + messageService.getMessage());
       }
   }
  1. 修改AppConfig类:
   package com.example;

   import org.springframework.context.annotation.Bean;
   import org.springframework.context.annotation.Configuration;

   @Configuration
   public class AppConfig {
       @Bean
       public MessageService messageService() {
           return new MessageServiceImpl();
       }

       @Bean
       public HelloWorld helloWorld() {
           HelloWorld helloWorld = new HelloWorld();
           helloWorld.setMessageService(messageService());
           return helloWorld;
       }
   }
  1. 运行App类,输出结果为:
   Your Message : Hello, World!

2.5 AOP(面向切面编程)

AOP是Spring框架的另一个核心特性,它允许开发者将横切关注点(如日志记录、事务管理)从业务逻辑中分离出来,从而提高代码的模块化。

2.5.1 创建切面

  1. pom.xml中添加AOP依赖:
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-aop</artifactId>
       <version>5.3.21</version>
   </dependency>
   <dependency>
       <groupId>org.aspectj</groupId>
       <artifactId>aspectjweaver</artifactId>
       <version>1.9.7</version>
   </dependency>
  1. 创建LoggingAspect类:
   package com.example;

   import org.aspectj.lang.annotation.Aspect;
   import org.aspectj.lang.annotation.Before;
   import org.springframework.stereotype.Component;

   @Aspect
   @Component
   public class LoggingAspect {
       @Before("execution(* com.example.MessageService.getMessage(..))")
       public void beforeAdvice() {
           System.out.println("Before method: getMessage()");
       }
   }
  1. 修改AppConfig类,启用AOP支持:
   package com.example;

   import org.springframework.context.annotation.Bean;
   import org.springframework.context.annotation.Configuration;
   import org.springframework.context.annotation.EnableAspectJAutoProxy;

   @Configuration
   @EnableAspectJAutoProxy
   public class AppConfig {
       @Bean
       public MessageService messageService() {
           return new MessageServiceImpl();
       }

       @Bean
       public HelloWorld helloWorld(MessageService messageService) {
           return new HelloWorld(messageService);
       }
   }
  1. 运行App类,输出结果为:
   Before method: getMessage()
   Your Message : Hello, World!

2.6 事务管理

Spring框架提供了对事务管理的支持,可以通过声明式事务管理简化事务代码。

2.6.1 配置事务管理器

  1. pom.xml中添加事务管理依赖:
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-tx</artifactId>
       <version>5.3.21</version>
   </dependency>
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-jdbc</artifactId>
       <version>5.3.21</version>
   </dependency>
   <dependency>
       <groupId>com.h2database</groupId>
       <artifactId>h2</artifactId>
       <version>1.4.200</version>
   </dependency>
  1. 创建DataSourcePlatformTransactionManager的Bean:
   package com.example;

   import org.springframework.context.annotation.Bean;
   import org.springframework.context.annotation.Configuration;
   import org.springframework.jdbc.datasource.DriverManagerDataSource;
   import org.springframework.transaction.PlatformTransactionManager;
   import org.springframework.transaction.annotation.EnableTransactionManagement;
   import org.springframework.transaction.support.TransactionTemplate;

   import javax.sql.DataSource;

   @Configuration
   @EnableTransactionManagement
   public class AppConfig {
       @Bean
       public DataSource dataSource() {
           DriverManagerDataSource dataSource = new DriverManagerDataSource();
           dataSource.setDriverClassName("org.h2.Driver");
           dataSource.setUrl("jdbc:h2:mem:testdb");
           dataSource.setUsername("sa");
           dataSource.setPassword("");
           return dataSource;
       }

       @Bean
       public PlatformTransactionManager transactionManager(DataSource dataSource) {
           return new DataSourceTransactionManager(dataSource);
       }

       @Bean
       public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
           return new TransactionTemplate(transactionManager);
       }
   }
  1. 创建UserService类:
   package com.example;

   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.stereotype.Service;
   import org.springframework.transaction.annotation.Transactional;

   @Service
   public class UserService {
       @Autowired
       private UserRepository userRepository;

       @Transactional
       public void addUser(String name) {
           userRepository.addUser(name);
           if (name.equals("error")) {
               throw new RuntimeException("Simulated error");
           }
       }
   }
  1. 创建UserRepository类:
   package com.example;

   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.jdbc.core.JdbcTemplate;
   import org.springframework.stereotype.Repository;

   @Repository
   public class UserRepository {
       @Autowired
       private JdbcTemplate jdbcTemplate;

       public void addUser(String name) {
           jdbcTemplate.update("INSERT INTO users (name) VALUES (?)", name);
       }
   }
  1. 创建主类App
   package com.example;

   import org.springframework.context.ApplicationContext;
   import org.springframework.context.annotation.AnnotationConfigApplicationContext;

   public class App {
       public static void main(String[] args) {
           ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
           UserService userService = context.getBean(UserService.class);

           try {
               userService.addUser("John");
               userService.addUser("error");
           } catch (Exception e) {
               System.out.println("Transaction rolled back: " + e.getMessage());
           }
       }
   }
  1. 运行App类,输出结果为:
   Transaction rolled back: Simulated error

3. 总结

本文详细介绍了如何简单使用Spring框架,包括环境准备、项目创建、Spring容器配置、依赖注入、AOP和事务管理等内容。通过本文的学习,读者可以快速上手Spring框架,并掌握其核心特性。Spring框架的强大功能和灵活性使其成为Java开发中不可或缺的工具,希望本文能为初学者提供有价值的参考。

推荐阅读:
  1. ansible简单使用
  2. xss简单使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring

上一篇:Dropshare 5 for mac工具有什么用

下一篇:DaVinci Resolve Studio 16 for Mac软件有什么用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》