亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

在service層注入mapper時報空指針的解決

 更新時間:2021年06月17日 16:15:34   作者:陸跑跑已胖哭 �  
這篇文章主要介紹了在service層注入mapper時報空指針的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

在service層注入mapper時報空指針

今天又遇到一個極其刁鉆的問題,廢話不多說先上代碼,測試單元

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBoot_Run.class)
@ContextConfiguration(locations = { "classpath:mybatis/mappers/RevMapper.xml" })
public class TestTransaction {
 @Autowired
 RevMapper remapper;
 @Test
 public void testInsert() {
  ReData data = new ReData();
  data.setReTime(new Date()).setSeID("fdewfcdsfdssdfdsf").setSendDate(new Date());
  remapper.insertObject(data);
 }

然后是service代碼

public class ReService {
 
 @Autowired
 private RevMapper reMapper;
 private Socket socket=null;
 private BufferedReader br=null;
 private PrintWriter pw=null;
 public void recevice() {
  try {
    //創(chuàng)建服務(wù)器,并開放3081端口
      ServerSocket serv

RevMapper 類在測試的時候注入的好好地,為毛在service中就是空,一直空,空空空?。。?/p>

網(wǎng)上說的@mapperScan還有@mapper的注解我都加了一遍,這是為毛!?。。。?/p>

在博覽全部大神的CSDN中,我發(fā)現(xiàn)大家都是抄過來抄過去,小弟佩服??!

解決?。?!

因為我在啟動類是這樣寫的

@SpringBootApplication(exclude=DataSourceAutoConfiguration.class)
@MapperScan(“cn.yungtay.mapper”)
public class SpringBoot_Run {
public static void main(String[] args) {
 SpringApplication.run(SpringBoot_Run.class, args);
 ReMapper re=new ReMapper();
 re.receive;
}
}

厲害的歐巴們不要噴,我第一反應(yīng)是這樣的??!

問題出來了,當一個對象是new出來的時候,他是不交給spring管理的,所以對象根本注入不進去,null是理所當然的

第二個問題,你想一個方法隨著主啟動類而啟動,你可以這么干

@Service
public class ReService implements ApplicationRunner{
@Autowired
private RevMapper reMapper;
private Socket socket=null;
。。。。。。。。。。。。。
@Override
public void run(ApplicationArguments args) throws Exception {
 // TODO Auto-generated method stub
 你所需要啟動的方法XXXXXXXX
}

感覺自己又智慧了一點!

springmvc普通類(非control,service)注入mapper為null

在給項目寫一個定時器的時候,需要用到注入mapper進行數(shù)據(jù)庫操作,用像serviceimpl里的注入

@Autowired
UserMapper usermapper; 

無效,debug后發(fā)現(xiàn)usemapper為null,說明沒有注入成功

后看到其他文章知道了new出來的thread不在spring的容器中,所以無法注入成功,獲得bean

但是按照他的方法依舊為null,他的想法是主動注入bean,應(yīng)該是對的。

不過我這個可能有點特殊,于是最后只能使用終極大法

ApplicationContext  ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
usermapper = (UserMapper) ac.getBean("UserMapper");
usermapper.deleteAllCookies();

不要忘了給mapper個名字,例

@Repository(value="UserMapper")
public interface UserMapper {
public List<User> selectByExample(@Param("username1")String username,@Param("password")String password);
public int insertToken(@Param("username1")String username,@Param("token")String token);
public String checkToken(String token);
public int logout(@Param("username1")String username,@Param("token")String token);
public int deleteAllCookies();
}

這個方法主觀上感覺不是很好,先這樣吧!

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論