Spring Annotation(注解) @Component




@Component @Service @Controller @Repository

a)     初始化的名字默认为类名首字母小写

b)     可以指定初始化bean的名字


StuDaoImpl:

package com.mth.impl;

import org.springframework.stereotype.Component;

import com.mth.bean.Student;
import com.mth.dao.IStuDao;

/**
 * 
 * @ClassName: StuDaoImpl
 * @Description: @Component("stuDao")起个名字叫做stuDao
 * @author mth 75100313@qq.com
 * @date 2014-1-19 下午10:13:23
 * 
 */

@Component("stuDao")
public class StuDaoImpl implements IStuDao {

	@Override
	public void saveStu(Student stu) {
		System.out.println("保存学生");

	}

}

Service:

package com.mth.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.mth.bean.Student;
import com.mth.dao.IStuDao;

@Component("stuSer")
public class Service {
	private IStuDao dao;

	public IStuDao getDao() {
		return dao;
	}
	// 指定当前需要注入的资源 与Component当中的值进行匹配
	@Resource(name = "stuDao")
	public void setDao(IStuDao dao) {
		this.dao = dao;
	}

	public void saveStu(Student student) {
		dao.saveStu(student);
	}

}

applicationContext.xml配置:

<?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-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
	<!--	<context:annotation-config />可以不写-->
	<!--在com.mth开头的所有包下扫描,如果扫描到类上面有@Component就会创建一个对象放到容器中。-->
	<context:component-scan base-package="com.mth"></context:component-scan>

</beans>


测试代码:

package com.mth.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mth.bean.Student;
import com.mth.service.Service;

public class Test {

	/**
	 * @Title: main
	 * @Description: 测试Spring注解
	 * @param @param args 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		// getBean参数 必须是service类上面@Component("stuSer")里面的参数
		Service service = (Service) context.getBean("stuSer");
		service.saveStu(new Student());
	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值