12.6 服务层功能实现

12.6 服务层功能实现

BookService.java

/MyBookApp/src/com/service/BookService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.service;

import java.util.List;
import com.domain.Book;

public interface BookService {
/**
* 查找所有的图书.
*
* @return Book对象的List集合.
*/
List<Book> getAllBooks();
}

BookServiceImpl.java

/MyBookApp/src/com/service/BookServiceImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.domain.Book;
import com.mapper.BookMapper;

/**
* Book服务层接口实现类.
*/
// @Service("bookService")注解高数Spring创建当前类的一个名为bookService的bean.
@Service("bookService")
public class BookServiceImpl implements BookService {
/**
* 自动注入BookMapper.
*/
@Autowired
private BookMapper bookMapper;

/**
* BookService接口的getAllBooks()方法的实现.
*
* @see{BookService}
*/
@Override
public List<Book> getAllBooks() {
return bookMapper.selectAllBooks();
}
}

UserService.java

/MyBookApp/src/com/service/UserService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.service;

import com.domain.User;

public interface UserService {
/**
* 判断用户登录.
*
* @param loginname
* @param password
* @return 找到用户则返回User对象,找不到返回null
*/
User login(String loginname, String password);
}

UserServiceImpl.java

/MyBookApp/src/com/service/UserServiceImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.domain.User;
/**
* User服务层接口实现.
*/
// @Service("userService")表示当前类作为Spring的一个bean,名为userService
import com.mapper.UserMapper;

@Service("userService")
public class UserServiceImpl implements UserService {
/**
* 自动注入UserMapper
*/
@Autowired
private UserMapper userMapper;

/**
* UserServiec接口的login方法实现.
*
* @see{UserService}
*/
@Override
public User login(String loginname, String password) {
return userMapper.selectUserByLoginnamePassword(loginname, password);
}
}

服务层使用了Spring@Autowired注解自动注入持久层的Mapper对象,并且使用了@Service注解将类注释成为SpringBean