【Spring】注解注入bean

2.5以后出现的新特性,再也不用再beans.xml里面配置过多的bean了    

<?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="com.gaodml"></context:component-scan>

</beans> 



通过注释的方法,指名对应的组件
 @Service      用于标识业务层组件
 @Controller  用于标识控制层组件
 @Repository 用于标识数据访问组件,DAO组件
 @Component 组件,当不好归类的时候,我们使用这个进行标识

package com.gaodml.spring.personserviceimpl;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gaodml.spring.persondao.PersonDao;
import com.gaodml.spring.personservice.PersonService;

@Service
public class PersonServiceBean implements PersonService {
	
	@Resource
	private PersonDao personDao;
	
	@Override
	public void save(){
		System.out.println("save()方法调用");
		personDao.add();
	}

	public PersonServiceBean() {
		
	}

}
 


package com.gaodml.spring.persondaoimpl;

import org.springframework.stereotype.Repository;

import com.gaodml.spring.persondao.PersonDao;

@Repository
public class PersonDaoBean implements PersonDao {

	/*
	 * (non-Javadoc)
	 * 
	 * @see PersonDao#add()
	 */
	@Override
	public void add() {
		System.out.println("add()方法调用");
	}

}

package com.gaodml.spring.test;

import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gaodml.spring.personservice.PersonService;

public class Springtest {

	@Test
	public void test() {

		AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(
				"beans.xml");
		PersonService personService = (PersonService) ctx
				.getBean("personServiceBean");
		System.out.println(personService);
		personService.save();
		ctx.close();
	}

}



红色部分,因为我们没有在bean.xml 里面配置信息,所以根本不知道这个id,那么,默认规定。

填写对应Bean的名字,不过首字母要小写 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值