spring中常用注解小结
@SpringBootApplication
标注在类上,表示此类是SpringBoot的启动类,springboot项目启动此类main函数便可启动。
@MapperScan(“xxx.dao”)
添加在springboot启动器类上,指定要变成实现类的接口所在的包,包下面的所有接口在编译后都会产生响应的实体类
@SpringBootApplication
@MapperScan("com.lqk.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Repository
将dao实现类(自定义的实现类)标识为bean
@Configuration
标注在类上,表明当前类是一个配置类,是方法bean的源
@Controller
标注在类上,表明当前类是一个控制器类
@ResponseBody
将方法返回的对象通过适当的转换器转换为制定的格式之后,写入到response中的body区,通常用来返回JSON数据或者XML
@RestController
等同于@Controller+@ResponseBody ,当类中所有方法返回的不是跳转页面时可以标注类使用,这样就不用在每个方法上加上@ResponseBody
@RestController
public class HelloController {
@Autowired
private DataSource dataSource;
@GetMapping("/hello")
public String hello(){
return "hello spring boot" + dataSource;
}
}
@Autowired
自动装配实例(通过类型实现依赖注入),在spring容器中找到对应类型的类并将其注入,如果一个类有多个bean值,需要配合@Qualifier指定名称
public class UserService {
@Autowired
@Qualifier(name="userDao1")
private UserDao userDao;
}
@Resource
自动装配实例(通过名称实现依赖注入),此注解有name和type属性,可以直接指定想要注入的bean
public class UserService {
@Resource
private UserDao userDao;//默认属性名为userDao的bean对象
@Resource(name="studentDao")
private StudentDao studentDao;//指定名称
@Resource(type="TeacherDao")
private TeacherDao teacherDao;//指定类型
@Resource(name="manDao",type="ManDao")
private ManDao manDao;//都指定
}
@RequestMapping("/bill")
controller中匹配请求路径
@Service
标注在service层实现类上面,spring容器会创建一个service接口的实现类
@Component
泛指组件,当一个类不属于dao层、service层、controller层时,比如工具类就需要使用此注解
@Data
此注解可以自动为类提供get、set、equals、hashCode、toString方法,不用自己手动编写,需要安装lombok插件并添加依赖
@Accessors
该注解控制getter和setter方法的形式。
fluent为true:表示getter和setter方法的方法名都是属性名,且setter方法返回当前对象
@Data
@Accessors(fluent = true)
class User {
private Integer id;
private String name;
// 生成的getter和setter方法如下,方法体略
public Integer id(){}
public User id(Integer id){}
public String name(){}
public User name(String name){}
}
chain为true:则setter方法返回当前对象
@Data
@Accessors(chain = true)
class User {
private Integer id;
private String name;
// 生成的setter方法如下,方法体略
public User setId(Integer id){}
public User setName(String name){}
}
prefix属性,getter和setter方法会忽视属性名 的指定前缀
@Data
@Accessors(prefix = "f")
class User {
private Integer fId;
private String fName;
// 生成的getter和setter方法如下,方法体略
public Integer id(){}
public void id(Integer id){}
public String name(){}
public void name(String name){}
}
@Table
表名和实体类名不一致时,使用name属性指定表名
@Table(name = "bill_")
public class Bill {}
@Id
指定主键
@GeneratedValue
提供主键的生成策略
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//主键自增长的方式
private Integer id;
@Column
当属名和列名不一致时,指定对应列名
@Column(name = "title_")
private String title;
@Transient
在实体类中如果想要添加数据表中不存在的字段,就需要用到此注解