Spring部分
1.声明bean的注解
@Component组件,没有明确的角色
作用:放在类上,表示这个类由spring容器去管理,由spring创建对象放到容器中
属性:默认bean的id是:类的名字,首字母小写
/**
* 账户类
*/
@Component
public class Account {
private Integer id; //编号
private String name; //姓名
private Double money; //余额
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
@Service在业务逻辑层使用(service层)
@Repository在数据访问层使用(dao层)
@Controller在展现层使用,控制层的生命
这三个标签的功能与@Component是一样的,只是语义上的区别。
2.注入bean的注解
@Autowired:
- 按类型匹配
- 如果有多个相同的类型,按名字匹配
- 如果找不到名字,抛出异常
位置:1.成员变量 2.成员方法
作用:
- 默认按类型匹配的方式从容器中去查找相应的对象,并且注入给这个属性或方法
- 如果存在多个相同的类型,按名字匹配的方式去注入对象
@Component("user")
public class User1 {
@Autowired
private String username;
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
'}';
}
}
3.java配置类相关注解
@Configuration 声明当前类为配置类,相当于xml形式的Spring配置(类上)
@Bean 注解在方法上,声明当前方法的返回值为一个bean,替代xml中的方式(方法上)
@Configuration 声明当前类为配置类,其中内部组合了@Component注解,表明这个类是一个bean(类上)
@ComponentScan 用于对Component进行扫描,相当于xml中的(类上)
@WishlyConfiguration 为@Configuration与@ComponentScan的组合注解,可以替代这两个注解
4.切面(AOP)相关注解
Spring支持AspectJ的注解式切面编程
@Aspect 声明一个切面(类上)
使用@After、@Before、@Around定义建言(advice),可直接将拦截规则(切点)作为参数。
@After 在方法执行之后执行(方法上)
@Before 在方法执行之前执行(方法上)
/**
* 次要的业务:切面类
*/
@Component //把这个类加到Spring容器中
@Aspect //这个类是切面类
public class LogAspect {
@Pointcut("execution(* com.itheima.service..*.*(..))") //切面表达式,这是一个空方法,作用:创建切面表达式的
public void pt() {
}
@Before("pt()")
public void before() {
System.out.println("前置通知");
}
@AfterReturning("pt()")
public void afterReturn() {
System.out.println("后置通知");
}
@AfterThrowing("pt()")
public void afterThrowing() {
System.out.println("异常通知");
}
@After("pt()")
public void after() {
System.out.println("最终通知");
}
}
@Around 在方法执行之前与之后执行(方法上)
/**
* 次要的业务:切面类
*/
@Component //把这个类加到Spring容器中
@Aspect //这个类是切面类
public class LogAspect {
@Pointcut("execution(* com.itheima.service..*.*(..))") //切面表达式,这是一个空方法,作用:创建切面表达式的
public void pt() {
}
/**
* 环绕通知
*/
@Around("pt()")
public Object around(ProceedingJoinPoint joinPoint) {
Object result = null;
try {
System.out.println("前置通知");
//调用目标方法
result = joinPoint.proceed();
System.out.println("后置通知");
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("异常通知");
} finally {
System.out.println("最终通知");
}
//返回方法的返回值
return result;
}
}
@PointCut 声明切点
在java配置类中使用@EnableAspectJAutoProxy注解开启Spring对AspectJ代理的支持(类上)
5.@Bean的属性支持
@Scope 设置Spring容器如何新建Bean实例(方法上,得有@Bean)
@Component("user")
@Scope("prototype")
public class User5 {
}
其设置类型包括:
Singleton (单例,一个Spring容器中只有一个bean实例,默认模式),
Protetype (每次调用新建一个bean),
Request (web项目中,给每个http request新建一个bean),
Session (web项目中,给每个http session新建一个bean),
GlobalSession(给每一个 global http session新建一个Bean实例)
@StepScope 在Spring Batch中还有涉及
@PostConstruct 由JSR-250提供,在构造函数执行完之后执行,等价于xml配置文件中bean的initMethod
@PreDestory 由JSR-250提供,在Bean销毁之前执行,等价于xml配置文件中bean的destroyMethod
6.@Value注解
@Value为属性注入值
支持如下方式的注入:
注入普通字符
@Value("Kobe")
String name;
注入操作系统属性
@Value("#{systemProperties['os.name']}")
String name;
注入配置文件
@Value("${book.name}")
String bookName;
注入配置使用方法:
① 编写配置文件(test.properties)
book.name=《三体》
② @PropertySource 加载配置文件(类上)
@PropertySource("classpath:com/hgs/hello/test/test.propertie")
③ 还需配置一个PropertySourcesPlaceholderConfigurer的bean。
7.测试相关注解
@RunWith 运行器,Spring中通常用于对JUnit的支持
@ContextConfiguration 用来加载配置ApplicationContext,其中classes属性用来加载配置类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestAccount {
@Autowired
private AccountService accountService;
@Test
public void testUpdate() {
//System.out.println(accountService.getClass());
//获取业务对象,执行业务方法
accountService.update("Jack");
}
}
SpringMVC部分
@EnableWebMvc 在配置类中开启Web MVC的配置支持,如一些ViewResolver或者MessageConverter等,若无此句,重写WebMvcConfigurerAdapter方法(用于对SpringMVC的配置)。
@Controller 声明该类为SpringMVC中的Controller
@RequestMapping 用于映射Web请求,包括访问路径和参数(类或方法上)
@ResponseBody 支持将返回值放在response内,而不是一个页面,通常用户返回json数据(返回值旁或方法上)
@RequestBody 允许request的参数在request体中,而不是在直接连接在地址后面。(放在参数前)
@Controller
public class JsonController {
//返回的是一个java对象,然后把java对象转换json.
//请求参数是json字符串的时候需要转换为java对象,那么需要使用@RequestBody
//如果返回值需要返回的是一个json对象,那么只需要添加@repsonseBody注解即可
@RequestMapping("/jsonData")
@ResponseBody
public User jsonData(@RequestBody User user){
System.out.println("接收到的对象:"+user);
User user2 = new User(220,"狗剩");
return user2;
}
}
@PathVariable 用于接收路径参数,比如@RequestMapping(“/hello/{name}”)申明的路径,将注解放在参数中前,即可获取该值,通常作为Restful的接口实现方法。
//查询单个
/*
{参数名称}: 参数占位符
@PathVariable: 获取请求路径的参数给形参注入
*/
@RequestMapping(value="/{id}/{name}",method= RequestMethod.GET) //限制该方法只能是post请求访问
public String findByCondition(@PathVariable("id") Integer id, @PathVariable("name") String name){
System.out.println("id:"+id+" 姓名:"+ name);
return "success";
}
@RestController 该注解为一个组合注解,相当于@Controller和@ResponseBody的组合,注解在类上,意味着,该Controller的所有方法都默认加上了@ResponseBody。
@ControllerAdvice 通过该注解,我们可以将对于控制器的全局配置放置在同一个位置,注解了@Controller的类的方法可使用@ExceptionHandler、@InitBinder、@ModelAttribute注解到方法上,
这对所有注解了 @RequestMapping的控制器内的方法有效。
@ExceptionHandler 用于全局处理控制器里的异常
@InitBinder 用来设置WebDataBinder,WebDataBinder用来自动绑定前台请求参数到Model中。
@ModelAttribute 本来的作用是绑定键值对到Model里,在@ControllerAdvice中是让全局的@RequestMapping都能获得在此处设置的键值对。