您的位置:首页 > 编程语言 > Java开发

【Spring】注解注入bean

2015-02-25 18:41 232 查看
[align=center][/align]

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的名字,不过首字母要小写

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: