spring学习第三天

Bean的属性注入–基于注解方式

IoC容器装配Bean , 基于注解配置方式

  • Spring2.5 引入注解去定义Bean

    • @Component 描述Spring框架中Bean
  • Xml:头文件中加入context路径:

  • 最好直接从dsd-config.html中复制过来相应的代码段

    <?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">
    
    <!-- bean definitions here -->
    
    </beans>
    
  • 配置提示操作

  • 将红框中地址复制到Key中

  • 引入component-scan标签:,告诉Spring要去扫描哪些包下的类。

  • Spring的框架中提供了与@Component注解等效的三个注解:

    • @Repository 用于对DAO实现类进行标注
    • @Service 用于对Service实现类进行标注
    • @Controller 用于对Controller实现类进行标注
  • 三个注解是为了让标注类本身的用途清晰,Spring在后续版本会对其增强

自动装配 Bean

  • 使用@Autowired 进行自动注入
  • @Service 标注业务类
  • @Repository 标注DAO
  • @Autowired 默认按照类型进行注入

    • 如果存在两个相同Bean类型,则按照名称注入
    • @Autowired 注入时可以针对成员变量或者setter方法
  • 通过@Autowired的required属性,设置一定要找到匹配的Bean,默认为true,为false时表示对异常不关心。

  • 使用@Qualifier指定注入Bean的名称

  • 使用Qualifier 指定Bean名称后,注解Bean必须指定相同名称

普通属性

  • @Value(value=”itcast”)
  • private String info;

    对象属性

  • 按类型注入

    • @Autowired:自动装配默认使用类型注入.
  • 按名称进行注入

    • @Autowired 中有一个属性required,默认为true,为false时表示对异常不关心。
    • @Qualifier(“userDao”) 按名称进行注入.

标准注解@Resource

  • Spring提供对JSR-250中定义@Resource标准注解的支持@Resource和@Autowired注解功能相似

  • 下面两个例子等价

    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;
    
    @Resource(name="userDao")
    private UserDao userDao;
    

Bean其他的属性的配置

  • 配置Bean初始化方法和销毁方法:
    • init-method 和 destroy-method.
    • @PostConstruct : 初始化
    • @PreDestroy : 销毁

配置Bean的作用范围

  • 使用注解配置的Bean和配置的一样,默认作用范围都是singleton
    • @Scope注解用于指定Bean的作用范围

Spring3.0可以 使用Java类提供Bean定义信息

  • Spring3.0以JavaConfig为核心,提供使用Java类定义Bean信息的方法
    • @Configuration 指定POJO类为Spring提供Bean定义信息,代表此类就是一个配置类。
    • @Bean 提供一个Bean定义信息
  • 之前已经通过 component-scan标签 对配置类进行了扫描,故这里不需要再进行手动配置扫描了。

    @Configuration public class BeanConfig {

    @Bean(name="car")
    public Car showCar(){
        Car car = new Car();
        car.setName("长安");
        car.setPrice(40000d);
        return car;
    }
    
    @Bean(name="product")
    public Product initProduct(){
        Product product = new Product();
        product.setName("空调");
        product.setPrice(3000d);
        return product;
    }
    

    }

实际开发中使用XML还是注解 ## - XML: - bean管理 - 注解: - 注入属性的时候比较方便 - 两种方式结合;一般使用XML注册Bean,使用注解进行属性的注入

Spring整合web开发

  • 正常整合Servlet和Spring没有问题的,但是每次执行Servlet的时候加载Spring配置以及加载Spring环境
  • 解决办法:

    • 将加载的信息内容放到ServletContext中.ServletContext对象是全局的对象。服务器启动的时候创建的,在创建ServletContext的时候就加载Spring的环境。
    • ServletContextListener:用于监听ServletContext对象的创建和销毁的.
    • 以上解决方法可以通过导入Spring web开发jar包来解决 : spring-web-3.2.0.RELEASE.jar

      web.xml中的配置

  • 将Spring容器初始化,交由web容器负责

  • 配置核心监听器 ContextLoaderListener

  • 配置全局参数contextConfigLocation

    • 用于指定Spring的框架的配置文件位置(因为:applicationContext.xml文件与默认位置不一致)

      <listener>
           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      
      </listener>
       <context-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:applicationContext.xml</param-value>
       </context-param>
      

获得WebApplicationContext对象

  • 因为Spring容器已经交由web容器初始化和管理,获得WebApplicationContext对象,需要依赖ServletContext对象 通常在Servlet中完成:

    WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

  • 另一种方式

    WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

  • eg:

  • web.xml

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
      <display-name></display-name>
     <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>
    
     <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
     </context-param>
    
      <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>cn.itcast.servlet.UserServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/userServlet</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
    

UserServlet & UserService public class UserServlet extends HttpServlet {

        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            /*ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                    "applicationContext.xml");*/
            WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

            UserService userService = (UserService) applicationContext
                    .getBean("userService");
            userService.sayHello();
        }



    public class UserService {

        public void sayHello(){
            System.out.println("Hello Spring web...");
        }
    }

Spring集成JUnit测试 - 1.程序中有Junit环境. - 2.导入Spring test测试jar包 - spring-test-3.2.0.RELEASE.jar - 3.测试代码:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations="classpath:applicationContext.xml")
        public class SpringTest {
            @Autowired
            private UserService userService;

            @Test
            public void demo 1(){
                userService.sayHello();
            }
    }