前面我们说的是数据持久层的dao对象的创建实现.现在我们希望加入业务逻辑层.那如何来做呢?
和使用xml实现bean装配一样,我们现在src下创建一个service包,里面定义UserService接口
package service;
public interface UserService {
void addUser();
void deleteUser();
}
src下有一个子包impl,里面定义 UserService接口的实现类UserServiceImpl
package service.impl;
import service.UserService;
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
}
@Override
public void deleteUser() {
}
}
由于我们想通过注解来实现UserServiceImpl这个类的创建,那们我们需要在类声明上面加上@...注解.由于考虑分层,我们这里最好使用@Service("userservice")这个注解,并起个名字"userservice"..由于在这里我们需要调用dao的方法,所以我们这里还需要添加一个成员属性 private UserDao dao;如果是以前,我们使用xml的方式,我们还需要setter方法或者构造方法.但是使用注解就什么都不用写,直接声明就可以了.但是这里dao的值哪里来呢?注意:前面我们已经让配置文件扫描dao这个包之后,已经在容器里拿到了userdao这个对象了,那我们这里就可以直接给声明好的UserDao这个成员属性上面标注@Autowired来注入.所以,更新后的UserServiceImpl的代码如下:
package service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import dao.UserDao;
import service.UserService;
@Service("userservice")
public class UserServiceImpl implements UserService {
@Autowired
@Qualifier("userdao")
private UserDao dao;
/*
* 以前我们使用xml的方式还需要些构造方法或者是setter方法,
* 使用注解就不用写了,但是有个问题,dao的值从哪里来呢?
*/
@Override
public void addUser() {
dao.addUser();
}
@Override
public void deleteUser() {
dao.deleteUser();
}
}
这里我们已经在实现类中都标注好了注释,这时候我们一定要记得在applicationContext.xml配置文件中让上下文去扫描这个service包里的内容.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="dao,service" ></context:component-scan>
</beans>
我们可以在context:component-scan base-package这个属性里面写多个包名,用","分隔
下面我们写一下测试类:这里我们需要通过容器得到的是UserService这个接口的实现类对象:
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;
public class Test {
public static void main(String[] args) {
ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = ac.getBean("userservice", UserService.class);
service.addUser();
service.deleteUser();
}
}
输出结果就不展示了,和前面一样的.
这里再次提醒一遍:我们写完注解后,一定要再配置文件中让上下文去扫描我们需要创建对象的类所在的包.