【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的名字,不过首字母要小写 |
相关文章推荐
- SSH下使用Spring注解自动注入bean
- Spring 配置bean, 注解方式配置 xml方式要生产set方法方便属性注入,注解方式不需要,利用反射机制注入
- 框架 day36 Spring3 入门,DI依赖注入,装配bean基于xml/注解, 整合Junit4,配置约束自动提示
- 用spring的注解建立bean与bean之间的关系组件装配及自动注入依赖对象
- Spring Bean装配--@Bean注解注入说明
- 零配置 之 12.2 注解实现Bean依赖注入 ——跟我学spring3
- Spring配置使用注解注入bean
- Spring 注解实现Bean依赖注入之@Qualifier
- Spring的bean管理——注解注入属性
- [java][spring]取得通过配置文件和注解注入的bean、取得当前数据库连接、取得Appli
- Spring 注解Autowired自动注入bean异常解决
- SSM框架项目搭建系列(五)—Spring之Bean的注解注入
- spring 在单例类中使用注解注入bean
- Spring Bean 注入 2 注解篇
- Spring中的注解配置-注入bean
- Spring系列【06】@Resource注解实现Bean的注入
- Spring中bean注入初始化方式—通过注解@Configuration @bean
- Spring中bean注入初始化方式—通过注解@Configuration @bean
- Spring Bean装配--@Qualifier结合@Autowired注解注入说明
- Spring中bean注入初始化方式—通过注解@Configuration @bean