目录
前言:
Web注解是一种强大的工具,能够让用户在Web页面上进行多样化的操作,实现在线协作和知识共享。它在促进信息共享、提高交流效率和推动多人合作方面具有巨大潜力。
注解:
@Component
案例:
package com.example.demo;
import org.springframework.stereotype.Component;
@Component // 将该类标记为一个组件
public class HelloWorld {
public void sayHello() {
System.out.println("Hello World!");
}
}
该注解在Web开发中的作用是将一个类标记为一个可被Spring容器管理的组件,实现依赖注入和自动化配置。
@Aspect
案例:
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before method: " + joinPoint.getSignature().getName());
}
@After("execution(* com.example.service.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("After method: " + joinPoint.getSignature().getName());
}
@AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "exception")
public void logException(JoinPoint joinPoint, Exception exception) {
System.out.println("Exception in method: " + joinPoint.getSignature().getName() + ", exception: " + exception.getMessage());
}
}
该注解在Web开发中的作用是将一个普通的 Java 类声明为切面,通过定义切点和切面逻辑,实现横切关注点的处理和对方法的增强。这样可以提高代码的可维护性、可重用性,并实现与业务逻辑的解耦
@Around
案例:
@Component
@Aspect
public class TransactionAspect {
@Around("@annotation(com.example.annotation.Transactional)")
public Object performTransaction(ProceedingJoinPoint joinPoint) throws Throwable {
// 在方法执行前进行事务开启操作
TransactionManager.beginTransaction();
Object result;
try {
// 执行切点方法
result = joinPoint.proceed();
// 在方法执行后进行事务提交操作
TransactionManager.commitTransaction();
} catch (Exception e) {
// 发生异常时进行事务回滚操作
TransactionManager.rollbackTransaction();
throw e;
}
return result;
}
}
该注解在Web开发中的作用是在切点方法执行前后插入自定义的逻辑,并可以控制切点方法的执行、统一处理横切关注点、修改切点方法的返回值等。通过使用 @Around 注解,可以实现与业务逻辑解耦的横切关注点处理和方法增强。
@Pointcut
案例:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class LoggingAspect {
@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceMethods() {
}
@Pointcut("execution(* com.example.controller.*.*(..))")
public void controllerMethods() {
}
@Pointcut("serviceMethods() || controllerMethods()")
public void allMethods() {
}
}
该注解可以让我们更灵活地定义切点,可以根据需要选择匹配的方法或类。在实际使用Spring AOP时,我们可以在切面类的通知方法上使用这些切点来指定切入点,并在对应的方法上触发切面逻辑
@Autowired
案例:
@Controller
public class UserController {
@Autowired
private UserService userService;
// 省略其他方法
}
该注解在Web开发中起到了简化代码、解决依赖冲突、自动装配对象等作用,提高了代码的可维护性和灵活性。
@Transient
案例:
@Entity
public class Order {
@Id
private Long id;
private BigDecimal totalPrice;
@Transient
private BigDecimal discountedPrice;
// getters and setters
}
该注解在Web开发中起到了标记某些字段为非持久化字段的作用,使得持久化框架不会将这些字段的值保存到数据库中。
@MappedSuperclass
案例:
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 其他共享的属性和方法...
}
@Entity
public class Order extends BaseEntity {
// Order特有的属性和方法...
}
@Entity
public class Customer extends BaseEntity {
// Customer特有的属性和方法...
}
该注解的作用是将一个类标识为映射到数据库表的超类。该注解通常用于建立共享属性和行为的父类,而不是实际映射到数据库表的实体类。
@Override
案例:
@Entity
public class Product {
@Override
public String toString() {
return "Product Details";
}
}
该注解通常用于标记一个方法是覆盖父类或实现接口中的方法。这个注解有助于提醒开发人员,帮助他们确保方法的正确性和一致性。
@GetMapping
案例:
@Controller
@RequestMapping("/example")
public class ExampleController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
@GetMapping({"/world", "/world2"})
public String world() {
return "world";
}
}
该注解的作用是将HTTP GET请求映射到对应的处理方法上,通过定义合适的URL路径,使得控制器能够正确地处理用户请求并返回相应的结果。
@RestController
案例:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
该注解的作用是将一个类标识为处理HTTP请求的控制器,并且将方法的返回值直接写入HTTP响应体中,使得构建RESTful风格的Web服务更加简单和方便。
@CrossOrigin
案例:
@RestController
@RequestMapping("/api")
public class UserController {
@CrossOrigin(origins = "http://example.com")
@GetMapping("/users")
public List<User> getUsers() {
// 返回用户列表
}
@CrossOrigin(origins = {"http://example.com", "http://example2.com"})
@PostMapping("/users")
public User createUser(@RequestBody User user) {
// 创建新用户
}
}
该注解可以在Spring Boot应用中方便地处理跨域请求,使得服务器端能够接受并处理来自不同域的请求。
@Bean
案例:
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserServiceImpl();
}
}
该解的作用是将一个方法标记为Bean,并将其返回的对象注册到Spring的应用上下文中,以供其他组件使用。
@Temporal
案例:
import javax.persistence.*;
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;
private String name;
@Temporal(TemporalType.DATE)
private java.util.Date birthDate;
// Getter and Setter methods
}
该注释的作用是告诉持久化提供程序将实体类属性映射到数据库中的日期、时间或日期时间类型。
总结:
总而言之,多使用注解可以提高代码的可读性和维护性,同时也可以减少重复的工作。