在spring学习4之注解配置中我们只是对单个实例进行注解,并没有 实际开发项目时候的三层,在此次讲解中,模拟三层架构进行使用配置。
一、dao层的开发
- 创建一个StudentDao的接口,并且创建一个sava方法,模拟数据库的保存。
package com.pp.demo2;
public interface StudentDao {
void save();
}
- 创建一个StudentDaoImpl类继承并实现StudentDao类
package com.pp.demo2;
import org.springframework.stereotype.Repository;
@Repository
public class StudentDaoImpl implements StudentDao {
public void save() {
System.out.println("保存了!");
}
}
二、service层的开发
- 创建一个StudentService的接口类,
package com.pp.demo2;
public interface StudentService {
public void learn();
}
- 创建一个StudentServiceImpl继承并实现StudentService类
package com.pp.demo2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao dao;
public void learn() {
System.out.println("service层");
dao.save();
}
}
三、控制层的开发
package com.pp.demo2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller(value = "student")
public class StudentController {
@Autowired
private StudentService service;
public void Test(){
service.learn();
}
}
四、编写TestStudent测试类
package com.pp.demo2;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestStudent {
@Test
public void fun(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentController student = (StudentController)context.getBean("student");
student.Test();
}
}
这里的代码中先加载 applicationContext.xml创建工厂,然后通过获取id 的形式去获取具体的那一个层,在这里获取的是student,通过 发现@Controller(value = “student”)层里面又student参数,然后机会实例化该层,并且可以使用该层下面的属性和方法。
扩展知识:
package com.pp.demo2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller(value = "student")
@Scope(value="singleton")
public class StudentController {
@Autowired
private StudentService service;
@Scope(value="singleton")
public void Test(){
service.learn();
}
}
以上代码中,更上面的实例内容是一样的内容,不一样的是多了一个Scope,该注解只能作用于类或者方法上,属性值又singleton和prototype两个值,singleton为单例模式,意思就是内存中至多只能创建一个类或者方法,二prototype多例模式可以创建多个。
源码地址:https://gitee.com/yangforever/project-learning/tree/master/demo/Spring/springday2