如下图:
网上都是改警告,又是删spring啥的。我觉得都不合适。
第一种方法(最佳),在mapper接口类上加@Repository注解
这是从spring2.0新增的一个注解,用于简化 Spring 的开发,实现数据访问。
相当于加上@Component注解。
不过注意,要在启动类里加@MappterScan(basePackage = "com.xxx.mapper)
第二种:改成这个。(原理是默认情况下true表示bean必须存在。false表示可以为null)
@Autowired(required = false)
@Autowired默认按类型装配(这个注解是属业spring的),默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用,如下:
@Autowired ()
@Qualifier ( "baseDao" )
private BaseDao baseDao;
第三种:把@Autowired改成@
Resource
@Resource(这个注解属于J2EE的),默认按照名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行安装名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
@Resource装配顺序
1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;
参考如下链接,就很详细
@Autowired 与@Resource的区别(详细)
------------分割线----
由于写的内容少,我直接扩展加些 相关的知识点
就是spring boot里 怎么使用注解和mapper的xml。
1.上面是使用注解。已经有图了。加@Selecter就可以了。
2.使用mapper.xml需要接口类写成如下。
package com.wf.mapper;
import com.wf.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository // 为了让idea 在@AutoWrite的时候能够检测到。需要 配合@MapperScan(basePackages = "com.wf.mapper")
public interface UserMapper {
List<User> findAll();
}
配置文件(注意和注解方式互相冲突,如果使用注解,下面第一行要注释掉)
#mybatis
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
mybatis.type-aliases-package=com.wf.pojo
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.wf.mapper.UserMapper">
<select id="findAll" resultType="user">
select * from user;
</select>
</mapper>
调用的时候方式不变
import com.wf.mapper.UserMapper;
import com.wf.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
// @Autowired(required = false)
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
}