三层架构的发展(续)

采用注解形式来实现自动创建对象

@Component(value = "student")
public class Student {

    @Value("自定义姓名")
    private  String name;

    private  int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age-5;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
<--组件扫描器   扫描com.spring下的所有类-->
<context:component-scan base-package="com.spring"></context:component-scan>

测试类

public class Client {
 
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //此处为获取bean中的对象,第一个参数为bean中的id,第二个为对象类型
        //当不写id的时候,默认的类名为类名首字母小写
        Student student = context.getBean("student",Student.class);
        System.out.println(student);
 
    }
}

 

注意:@Service    @Repository  @Controller也可以分别写在三层上,剩下步骤如楼上(其实service层也可以写@Component,@Controller,因为作用都是当成一个组件去看待,但是习惯不好)

 

注解三层代码的实现~

applicationContext.xml

<--组件扫描器   扫描以下俩个包下的所有类-->
<context:component-scan base-package="com.spring.bean,com.spring.mvc"></context:component-scan>
@Service
public class StudentServiceImpl implements StudentService {
 
    //如果有俩个类都实现了StudentDao,而且俩个类都写了注解,那么就不知道他该创建那个对象了,所以就要用到楼下的注解来指定创建哪个类的对象
    //@Qualifier(value="studentDaoImpl")
    //使用此注解,spring可以自动帮你把Bean里面引用类的对象的setter/getter方法省略掉,它会自动帮你set/get。
    @Autowired
    private  StudentDao studentDao;
 
    public void register(Student student) {
        studentDao.insert(student);
    }
    
}

测试类

public class Client {
 
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //此处为获取bean中的对象,第一个参数为bean中的id,第二个为对象类型
        StudentService studentService = context.getBean("service",StudentService.class);
        studentService.register(null);
 
    }
}

 

 

个性签名:一个人在年轻的时候浪费自己的才华与天赋是一件非常可惜的事情

        如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

 

万水千山总是情,打赏5毛买辣条行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾! 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值