spring配置方式:

来源:互联网 发布:linux gbk 乱码 编辑:程序博客网 时间:2024/05/16 13:04
spring中配置方式可以完全使用注解也可以完全使用注解实现,但是大部分都是用xml加注解,这样不仅兼顾了效率,也提高了程序的可读性:
但是需要注意的是:
纯注解实现时:需配置扫描:

  <context:component-scan base-package="com.leige.an"/>

纯xml开发就不用讲解了:

xml加注解时需要注意的是:

所有的bean对象都要在xml中配置,需要注入时,我们使用注解:

@AutoWired 和 @Resource 进行使用


@service

@Controller

@Repository()不再建议使用了

这时需要配置:
  <context:annotation-config/>扫描的效率比纯注解高



spring 整合junit:


package com.leige.an;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * @author 使用spring整合junit开发时,我们不需要再写从xml获取上下文,得到bean之类的代码, * 我们只需要,配置@RunWith(SpringJUnit4ClassRunner.class),表示整合springjunit * @ContextConfiguration(locations="classpath:com/leige/an/beans.xml")表示从当前类下查找 * 否则会在src下查找 *使用@Autowired *按照类型注入 * */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations="classpath:com/leige/an/beans.xml")public class TestAP {@AutowiredUserAction userAction;@Testpublic void test() {/*String xmlPath="com/leige/an/beans.xml";ApplicationContext context=new ClassPathXmlApplicationContext(xmlPath);UserAction userAction=(UserAction) context.getBean("userAction");*/userAction.regist();}}


0 0