发表于: 2018-04-24 23:41:17

1 563


今天完成的事情:

Junit,spring和Mybatis的整合

1.pom.xml添加spring和Mybatis-spring依赖

参考资料:https://blog.csdn.net/dbeautifulLife/article/details/70260189?locationNum=2&fps=1,http://outofmemory.cn/java/spring/spring-DI-with-annotation-context-component-scan

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>1.3.2</version>
</dependency>
<!--spring-->
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>5.0.4.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
   <version>5.0.4.RELEASE</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>5.0.4.RELEASE</version>
</dependency>

2.添加spring配置

<!--引入jdbc配置-->
<context:property-placeholder location="classpath:dataSource.properties"/>
<!--扫描文件(自动将service层注入) -->
<context:component-scan base-package="com.study.javaMavenService"/>

component-scan  注解注入 ,base-package属性告诉spring要扫描的包

eg:

@Service public class PersonService 

{ @Autowired private PersonDao personDao; 

public Person getPerson(int id) { return personDao.selectPersonById(id); }

}

在Service类上使用了@Service注解修饰,在它的私有字段PersonDao上面有@Autowired注解修饰。@Service告诉spring容器,这是一个Service类,默认情况会自动加载它到spring容器里。而@Autowired注解告诉spring,这个字段是需要自动注入的。

@Scope("singleton")@Repository

public class PersonDao {

public Person selectPersonById(int id) { Person p = new Person(); p.setId(id); p.setName("Person name"); return p; }

}

在PersonDao类上面有两个注解,分别为@Scope和@Repository,前者指定此spring bean的scope是单例,你也可以根据需要将此bean指定为prototype,@Repository注解指定此类是一个容器类,是DA层类的实现。这个类我们只是简单的定义了一个selectPersonById方法,该方法的实现也是一个假的实现,只是声明了一个Person的新实例,然后设置了属性,返回他,在实际应用中DA层的类肯定是要从数据库或者其他存储中取数据的。

Dao层好像和Mappe层是一样的,所以按照这个例子尝试在原来的项目加上注解

ApinformationServiceImpl.java

@Service
public class ApinformationServiceImpl implements ApinformationService {
@Autowired
   private ApinformationMapper apinformationMapper ;
}

ApinformationMapper.java

@Scope("singleton")
@Repository
public interface ApinformationMapper {

public int insertApfo(Apinformation apinformation) throws Exception;
   public int updateUser (Apinformation apinformation, int id) throws Exception;
   public int deleteUser(int id) throws Exception;
   public Apinformation selectUserById(int id) throws Exception;
   public List<Apinformation> selectAllUser() throws Exception;

}

出现了一个警告

说不能自动注入,因为没有找到ApinformationMapper的bean,尝试将singleton改为prototype,警告依然存在,因为还有一个spring-mybatis.xml的配置文件还没配置,所以先把这个放一下.等配置文件全部写完后再看看还有警告么.

明天计划的事情:

Junit,spring和Mybatis的整合做完

遇到的问题:

因为今天没做太多东西,所以没什么问题
收获:

了解了下注解配置


返回列表 返回列表
评论

    分享到