1.关于Spring注解式开发
我们在用IOC依赖注入的时候,需要对每一个需要创建的对象配一个<bean>标签,也就是说,有几个需要的类对象,就需要在applicationContext.xml里面配几个。而基于注解式的开发,我们只需要在applicationContext.xml里面配一个组件扫描
<context:component-scan base-package="com"></context:component-scan>
2.注解式开发demo
(1)导包
除了6个IOC容器的基本包之外,还需要导入一个AOP的jar包spring-aop-4.2.4.RELEASE.jar。
(2)建立dao接口和实现类
package com.dao.impl; import org.springframework.stereotype.Repository; import com.dao.TestDao; @Repository("testDao") public class TestDaoImpl implements TestDao { @Override public void saySome() { // TODO Auto-generated method stub System.out.println("Spring注解开发 "); } }
@Repository("testDao")这一行相当于<bean id="testDao" >而且是dao层的.
(3)建立service接口和实现类
package com.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dao.TestDao; import com.service.TestService; @Service("testService") public class TestServiceImpl implements TestService { @Resource private TestDao testDao ; @Override public void saySome() { // TODO Auto-generated method stub testDao.saySome(); } }
同理@Service("testService"),相当于service层<bean id="testService" >
@Resource我们放在下面解释。
(4)配置applicationContext.xml。
只需要配一行
<context:component-scan base-package="com"></context:component-scan>
这里看一下我的包目录,就明白了。
这里只要写到包目录的跟下边就可在系统加载配置文件的时候创建该包下的类的对象。说白了就是dao实现类以及service实现类的对象已经创建好了。
然后我们写个测试类试一下。
(5)demo类
package com.demo; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.service.TestService; public class Test01 { @Test public void testSome(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); TestService testService = (TestService) context.getBean("testService"); testService.saySome(); } }
(6) 运行结果
3.Spring框架中bean管理的常用注解
(1) @Component:组件.(作用在类上)
(2) Spring中提供@Component的三个衍生注解:(功能目前来讲是一致的)
@Controller -- 作用在WEB层
@Service -- 作用在业务层
@Repository -- 作用在持久层
(3) @Value -- 用于注入普通类型
(4) @Autowired --默认按类型进行自动装配
@Service("testService") public class TestServiceImpl implements TestService { @Autowired private TestDao testDao ;
(5)@Qualifier -- 强制使用名称注入,一般配合@Autowired。
注意:如果容器中同一个类型的bean如果有多个,使用Autowried报错,找到多个同类型的bean,使用@Qualifier和Autowired组合配置,Qualifier指定将哪个bean注入进来。
@Service("testService") public class TestServiceImpl implements TestService { @Autowired @Qualifier("testDao") private TestDao testDao ;(6)@Resource -- 相当于@Autowired和@Qualifier一起使用
强调:Java提供的注解
属性使用name属性
@Service("testService") public class TestServiceImpl implements TestService { @Resource private TestDao testDao ;