SSM框架注解总结
Spring中的注解:
**@Component:**把资源对象交给spring来管理,相当于在xml中配置一个bean,此注解使用在实体bean的头部,等价于XML中配置的“”标签。
示例:
//value = "accountService":相当于配置了bean标签的id属性,我们也可以不写value的值默认bean的id是当前类的类名首字母小写accountServiceImpl,单独配置value时,可以省略value。 @Component("accountService") public class AccountServiceImpl implements AccountService { }
**@Controller、 @Service、 @Repository:**都是针对@Component注解的衍生注解,他们的作用及属性都是一样的,等价于XML中配置用于注入数据的“ ”标签,他们只不过是提供了更加明确的语义化。
- @Controller:一般用于表现层的注解。
- @Service:一般用于业务层的注解。
- @Repository:一般用于持久层的注解。
注意:如果注解中有且只有一个属性要赋值时,且名称是value,value在赋值时可以不写。
**@Autowired:**自动按照类型注入。当使用注解注入属性时,set方法可以省略。它只能注入其他bean类型。当有多个类型匹配时,使用要注入的对象的变量名称作为bean的id,在spring容器查找,找到了也可以注入成功,如果找不到就会报错。
示例:
@RestControllerpublic class MyController { //注入一个myService实体bean @Autowired private MyService myService; }
**@Qualifier:**在自动按照类型注入的基础之上,再按照Bean的id注入。它在给字段注入时不能独立使用,必须和@Autowire一起使用,但是给方法参数注入时,可以独立使用。
属性:
value:指定bean的id。
示例:
@RestControllerpublic class MyController { //指定将myService实体bean注入myServiceBean中 @Autowired @Qualifier("myService") private MyService myServiceBean; /** * 给craJdbcTemplate方法注入一个dataSource实体bean参数 * @param dataSource * @return */ public JdbcTemplate craJdbcTemplate(@Qualifier("dataSource") DataSource dataSource) { }}
**@Resource:**直接按照Bean的id注入。它也只能注入bean类型。
属性:
name:指定bean的id。
示例:
@RestControllerpublic class MyController { @Resource(name = "myService") private MyService myServiceBean; }
**@Value:**注入基本数据类型和String类型数据的
属性:
value:用于指定值
示例:
@RestControllerpublic class MyController { @Value("zahngsan") private String name; name="zahngsan" //将配置文件jdbc.properties中的数据注解到( driverClass="com.mysql.jdbc.Driver") @Value("${jdbc.driverClass}") private String driverClass; }
用于改变作用范围的:
**@Scope:**用于指定bean的作用范围,相当于:
属性:
value:指定范围的值。
取值:
singleton:默认的单例
prototype:多例
新注解说明:
**@Configuration:**用于指定当前类是一个spring配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration注解的类.class)。
/** * spring的配置类,相当于applicationContext.xml文件 */ @Configuration public class SpringConfiguration { }
**@ComponentScan:**用于指定spring在初始化容器时要扫描的包。作用和在spring的xml配置文件中的“ <context:component-scan base-package="cn.itcast"></context:component-scan>”
属性:
Value(单独使用可省略):用于指定要扫描的包。和标签中的basePackages属性作用一样。
示例:
/** * @ComponentScan("com.study")中的"com.study"是项目的包名,该注解默认会扫描该类所在的包下所有的配置类。 */ @Configuration @ComponentScan("com.study") public class SpringConfiguration { }
**@Bean:**该注解只能写在方法上,将方法的返回值作为一个bean,并且放入spring容器。id就是name的属性的值
属性:
name:给当前@Bean注解方法创建的对象指定一个名称(即bean的id)。
示例:
@Bean(name="dataSource") public DataSource createDataSource() throws Exception { ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setDriverClass("com.mysql.jdbc.Driver"); ds.setJdbcUrl("jdbc:mysql://localhost:3306/heima-26"); ds.setUser("root"); ds.setPassword("root"); return ds; }
@PropertySource:
用于加载.properties文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties配置文件中,就可以使用此注解指定properties配置文件的位置。
属性:
value[]:用于指定properties文件位置。如果是在类路径下,需要写上classpath:
示例:
@PropertySource(value = { "classpath:jdbc.properties" }) public class JdbcConfig { @Value("${jdbc.driver}") private String driverClass; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean(name = "dataSource") public DataSource createDataSource() throws Exception { ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setDriverClass(driverClass); ds.setJdbcUrl(url); ds.setUser(username); ds.setPassword(password); return ds; } }
**@Import:**用于导入其他配置类,在引入其他配置类时,其他类上可以不用再写@Configuration注解。当然,写上也没问题。
属性:
value[]:用于指定其他配置类的字节码。
示例:
@Configuration @ComponentScan("com.study") @Import(value = { JdbcConfig.class }) public class SpringConfiguration { } @Configuration//写不写都行 @PropertySource(value = { "classpath:jdbc.properties" }) public class JdbcConfig { }
Spring整合junit注解:
**@RunWith:**替换掉junit的运行器,换成一个可以初始化spring容器的运行器。
属性:
value:单独配置时,value属性名称可以省略,配置SpringJUnit4ClassRunner.class来代替原来junit的运行器
@ContextConfiguration: 加载配置类或者xml配置文件
属性:
value:用来指定xml配置文件的路径
class: 用来指定配置类
示例:自动的加载配置文件的信息
//表示spring整合junit使用spring容器的运行器
@RunWith(SpringJUnit4ClassRunner.class)
//表示加载xml的配置的文件即可完成配置文件的加载
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
配置Aop注解:
@EnableAspectJAutoProxy:
声明使用注解方式的AOP配置了:
@Configuration:
标注此类是一个配置的类相当于applicationContext.xml的加载配置的类:
@ComponentScan("com.study"):
标注此类相当于applicationContext.xml的加载配置的类,开启包的全局的扫描的方式:
@Configuration//标注此类是一个配置的类@ComponentScan("com.study")//扫描的类@EnableAspectJAutoProxy//声明使用注解方式的AOP配置了public class SpringConfiguration { }
@Aspect:
指定当前类是通知类,此注解使用在类上。
@Aspect//声明这是一个切面类(通知类)里面配置的有具体的通知的方法@Service//将此类放到容器中public class Logger { }
@Before:
前置通知方法:
@Before("execution(* com.study.serviceImpl.*.*(..))")public void beforePrintLog() { System.out.println("前置通知执行了"); }
@after-returning:
后置通知方法:
@AfterReturning("execution(* com.itheima.serviceImpl.*.*(..))")public void afterReturningPrintLog() { System.out.println("后置通知执行了"); }
@after-throwing:
异常拦截通知方法:
@AfterThrowing("execution(* com.study.serviceImpl.*.*(..))")public void afterThrowingPrintLog() { System.out.println("异常通知执行了"); }
@after:
后通知方法:
@AfterReturning("execution(* com.study.serviceImpl.*.*(..))")public void afterReturningPrintLog() { System.out.println("后置通知执行了"); }
@PointCut:
抽取切点表达式:
@Pointcut("execution(* com.study.serviceImpl.*.*(..))") public void pointJoint(){ }
@around:
环绕通知方法:
/** * 环绕通知 * 问题: * 当配置完环绕通知之后,没有业务层方法执行(切入点方法执行) * 分析: * 通过动态代理的代码分析,我们现在的环绕通知没有明确的切入点方法调用 * 解决: * spring框架为我们提供了一个接口,该接口可以作为环绕通知的方法参数来使用 * ProceedingJoinPoint。当环绕通知执行时,spring框架会为我们注入该接口的实现类。 * 它有一个方法proceed(),就相当于invoke,执行目标方法 * <p> * spring的环绕通知: * 它是spring为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。 */ @Around("pt1()") public Object around(ProceedingJoinPoint pjp) { try { System.out.println("增强了前置通知!"); Object obj = pjp.proceed(); System.out.println("增强了后置通知!"); return obj; } catch (Throwable e) { System.out.println("增强了异常通知!"); throw new RuntimeException(e); } finally { System.out.println("增强了最终通知!"); } }
基于注解的事务管理:
@Transactional:
@Transactional 注解可以被应用于接口定义和接口方法、类定义和类的 public 方法上。
- 注解使用在类上表明此类下的所有的方法是一个基于注解的事务
- 定义在接口上,只有接口的代理的实现的类可认为是基于注解的方法。因为注解不能被继承。
- 然而,请注意仅仅 @Transactional 注解的出现不足于开启事务行为,它仅仅是一种元数据,能够被可以识别。要开启注解的事物管理 tx:annotation-driven/。
SpringMvc中的注解:
@Controller:
Spring的Controller是Singleton的。这就意味着会被多个请求线程共享。因此,我们将控制器设计成无状态类。
@RequestMapping:
在类前面定义,则将url和类绑定;(如果该类里只有单个方法的话可以这样写,访问该地址直接调用该方法):
示例:
@Controller@RequestMapping("/getUser")public class UserController { //定义在方法上则会为方法生成一个请求的路径:@RequestMapping("/hello")public String getHello() { return "index";} //可以携带请求的参数 Rest风格(占位符)的映射:请求URL:http://localhost:8080/user/zhangsan/1001//@RequestMapping(value=“/user/{name}/{id} ")<==>name=zhangsan、id=1001//这种方式虽然和通配符“*”类似,却比通配符更加强大,占位符除了可以起到通配的作用,最精要的地方是在于它还可以传递参数。@RequestMapping(value="show4/{name}/{id}") public ModelAndView test4(){ ModelAndView mv = new ModelAndView(); mv.setViewName("hello"); mv.addObject("msg", "占位符的映射:"); return mv; }}
与其相关注解:
- **@GetMapping:**相当于@RequestMapping(method = RequestMethod.GET)
- **@PostMapping:**相当于@RequestMapping(method = RequestMethod.POST)
- **@PutMapping:**相当于@RequestMapping(method = RequestMethod.PUT)
- **@DeleteMapping:**相当于@RequestMapping(method = RequestMethod.DELETE)
@PathVariable:
与 Rest风格(占位符)的映射一起使用获取URL路径的参数数据:
@RequestMapping(value="/show4/{name}/{id}")//public ModelAndView test4(@PathVariable("name")String names,@PathVariable("id")Long userId) @PathVariable(“key”)中的key必须和对应的占位符中的参数名一致,而方法形参的参数名可任意取public ModelAndView test4(@PathVariable("name")String name,@PathVariable("id")Long id){ ModelAndView mv = new ModelAndView(); mv.setViewName("hello"); mv.addObject("msg", "占位符的映射:"+name+"..."+id); return mv;}
@RequestParam:
-
常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值:
-
用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST: GET模式下,这里使用了@PathVariable绑定输入参数,非常适合Restful风格。因为隐藏了参数与路径的关系,可以提升网站的安全性,静态化页面,降低恶意攻击风险。POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。
-
该注解有三个属性: value、required、defaultValue:value用来指定要传入值的id名称、 required用来指示参数是否必须绑定、defaultValue用来指定在前端没有传值的情况下限定默认的值。
@RequestMapping(value="show19")public String test19(Model model,@RequestParam(value="name")String name){ model.addAttribute("msg", "使用@RequestParam接收到的参数为:"+name); return "hello";} @RequestMapping(value = "show23")@ResponseStatus(value=HttpStatus.OK)//如果不响应页面,就需要响应状态public void test23(@RequestParam("name")String name, @RequestParam("age")Integer age, @RequestParam("isMarry")Boolean isMarry, //可以将on或者1转换为true,0转换为false. @RequestParam("income")Float income, @RequestParam("interests")String[] interests) { StringBuffer sb = new StringBuffer(); sb.append("name:"+name+"\n"); sb.append("age:"+age+"\n"); sb.append("isMarry:"+isMarry+"\n"); sb.append("income:"+income+"\n"); sb.append("interests:["); for (String inter : interests) { sb.append(inter+" "); } sb.append("]"); System.out.println(sb.toString());}
**@CookieValue:**使用方法同@RequestParam,只不过它是获取cookie的值。
@RequestMapping(value = "show22")public String test22(Model model, @CookieValue("JSESSIONID")String jsessionid) { model.addAttribute("msg", "jsessionid:" + jsessionid); return "hello";}
@ResponseBody:
当一个处理请求的方法标记为@ResponseBody时,表示该方法需要输出其他视图(json、xml),springmvc会通过默认的json转化器转化输出。
/** * 将list集合响应成json数据 * @return */@RequestMapping(value="show28")@ResponseBody//将数据响应成json格式的数据public List<User> test28() { List<User> list = new ArrayList<User>(); for(int i = 0;i< 20;i++) { User user = new User(); user.setId(i+1L); user.setUsername("zhangsan"+i); user.setName("张三"+i); user.setAge(18); list.add(user); } return list; }
**@RequestBody:**接收一个json并且转换成一个对象
/** * 将提交的json格式的数据封装到user对象中 * * @RequestBody():自动将json数据序列化成一个user对象 * @param model * @param user * @return */ @RequestMapping(value="show29") public String test29(Model model,@RequestBody()User user) { model.addAttribute("msg", user); return "hello"; }
@RestController:
有时如果在一个Contoller中所有的方法都是用来响应json格式数据的,那么如果有多个方法,就需要在多个方法上使用@ResponseBody,这样太麻烦,springmvc提供了一个@RestController,将该注解使用在Controller类上,那么该controller中的所有方法都默认是响应json格式的数据了。
Mybatis框架常用注解总结:
@Mapper:作用是为了把mapper这个DAO交给Spring容器管理,一般不用加,我们在XXXMapper.xml中的namespace中已经指定过了。
@Mapperpublic interface UserDAO { /** * 插入 * @param userDO */ public void insert(User user);}
@Param:
使用@Param注解为相应的查询接口传递值,但是具体SQL语句中的参数要与@Param中定义的参数保持一致。
//mapper接口定义List<Student> selectBetweenCreatedTimeAnno(@Param("begin")Date beginMonth, @Param("end")String endMonth); //SQL语句 <select id="getAssessRecord" resultMap="SmuAssess"> select * from smu_assess_table3 where occurMonth between #{begin} and #{end} </select>
@MapKey:
MyBatis使用@MapKey注解接收多个查询记录到Map中.
@MapKey("id") public Map<Integer,Map<String,Object>>getUsers(Map<String,Object>param); //具体的sql标签<select id="getUsers" resultType="java.util.Map" parameterType="java.util.Map"> select id,name,sex from t_user</select> //返回的结果是 {1={name:jasion,sex:1},2={name:jack,sex=1}}
文末给大家推一篇基于Maven构建SSM框架的详细教程,需要的小伙伴请点击我。
谢谢大家阅读学习,如有错误欢迎留言指正哈。