spring学习4之注解配置(续)

spring学习4之注解配置中我们只是对单个实例进行注解,并没有 实际开发项目时候的三层,在此次讲解中,模拟三层架构进行使用配置。

一、dao层的开发

  1. 创建一个StudentDao的接口,并且创建一个sava方法,模拟数据库的保存。
package com.pp.demo2;

public interface StudentDao {
    void save();
}
  1. 创建一个StudentDaoImpl类继承并实现StudentDao类
package com.pp.demo2;

import org.springframework.stereotype.Repository;

@Repository
public class StudentDaoImpl implements StudentDao {
    public void save() {
        System.out.println("保存了!");
    }
}

二、service层的开发

  1. 创建一个StudentService的接口类,
package com.pp.demo2;

public interface StudentService {
    public void learn();
}

  1. 创建一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值