• day38 16-Spring的Bean的装配:注解的方式


    Struts 2和hibernate也使用注解,但是使用注解在以后的开发中应用不多。但是可以说在整合的时候如何进行注解开发。在Spring中,注解必须会玩。

    package cn.itcast.spring3.demo1;
    
    import org.springframework.stereotype.Component;
    
    /**
     * 注解的方式装配Bean.
     * @author zhongzh
     *
     */
    //在Spring配置文件中<bean id="userService" class="cn.itcast.demo1.UserService">
    //其实也需要核心配置文件,只不过不是用来装配bean了,你得告诉Spring需要去哪些包下面去扫描.它得扫描到这些注解才行.它得去哪里扫描你得告诉人家才行
    //@Component(value="userService")
    @Component("userService")
    public class UserService {
        
         public void sayHello(){
             
             System.out.println("Hello Spring Annotation.....");
         }
    }
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- 基于注解的开发需要引入context命名空间。它就是用来配置去扫描哪些包的. -->
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:p="http://www.springframework.org/schema/p"
           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:annotation-config></context:annotation-config><!-- XML和注解混搭的时候用的 -->
    <!-- 告诉Spring你要扫描哪些包下的东西 -->
    <!--  
    <context:component-scan base-package="cn.itcast.spring3.demo1">
    
    -->
    <context:component-scan base-package="cn.itcast.spring3.demo1"><!-- 纯注解用扫描的就行 -->
    
    
    
    
    
    
    
    
    
    
    
    </context:component-scan>
    
    
    
    </beans>
    package cn.itcast.spring3.demo1;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    //注解的方式:都是将类装载到容器中.
    public class SpringTest1 {
       @Test
       public void demo1(){
           
          ApplicationContext  applicationContext  = new ClassPathXmlApplicationContext("applicationContext.xml");
          UserService userService = (UserService) applicationContext.getBean("userService");
          userService.sayHello();
       }
        
        
    }
  • 相关阅读:
    Gym 100989E
    解决Pycharm无法导入包问题 Unresolved reference
    模块介绍/time/os...
    列表/元组/字符串/字典/集合/文件/字符编码
    迭代器/生成器/装饰器 /Json & pickle 数据序列化
    network / shuangwangka / inner + outer
    performance python httprunner
    performance python locust
    web sec / fastjson safemode
    python 向下取整,向上取整,四舍五入
  • 原文地址:https://www.cnblogs.com/ZHONGZHENHUA/p/6727209.html
Copyright © 2020-2023  润新知