zoukankan      html  css  js  c++  java
  • Spring--->固定套路及注解说明

    1、新建项目导包

     <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.2.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
        </dependencies>

    2、新建beans.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="..." class="...">  
            <!-- collaborators and configuration for this bean go here -->
        </bean>
      //id就是对应的创建对象的名字,class是对应的类
        <bean id="..." class="...">
            <!-- collaborators and configuration for this bean go here -->
        </bean>
    
        <!-- more bean definitions go here -->
    
    </beans>

     测试

    @org.junit.Test
        public  void Test01() {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            User user = context.getBean("user", User.class);
            System.out.println(user.name);
        }

    3、注解说明

    自动装配

    -@Autowired(    @Nullable   =false 允许字段为null)自动装配通过类型,名字

    -@Qualifier(value="dog22") 指定bean为唯一值,配合@Autowired

    -@Resource  自动装配通过类型名字

    四个功能都一样,都是代表将某个类注册到Spring,装配Bean

    -@Component  组件放在类上,说明被托管了,就是bean

    -@Repository  【dao】

    -@Service   【server】

    -@Controller  【controller】

    //  @Component组件等价于<bean name="user" class="com.xian.dao.User"/>
    @Component
    public class User {
        public String name="hanhanhan";
    }

    -@Value  放在set方法上效果一样

      // @Value等价于<property name="name" value="hanh"/>
        @Value("hanhanhan")
        public String name;

    作用域

    -@Scope("singleton")  作用域(单例模式)

    xml与注解

    • xml更万能,适用于任何场景,维护更方便

    • 注解不是自己的类使用不了,维护相对复杂

    最佳状态:

    xml只管理Bean

    注解完成值的注入

    注意

    必须让注解生效,就必须开启注解的支持

        <context:component-scan base-package="com.xian"/>
        <context:annotation-config/>

    4、使用Java配置Spring

    JavaConfig

  • 相关阅读:
    垃圾分类科普小游戏-体感垃圾分类-互动环境保护宣传软件
    卧式互动触摸查询一体机-智能触屏服务系统-触摸一体机
    卧式触摸查询一体机-政务查询触控系统-液晶多媒体触摸一体机
    卧式触摸屏自助查询一体机-智能触控一体机软件-自助终端机
    卧式触摸查询互动一体机-自助终端机-智慧城市办事大厅自助服务设备
    恒生内推
    Redis5设计与源码分析读后感(一)认识Redis
    Java Web学习(十二)Tomcat核心
    Java Web学习(四)http协议
    算法学习(三)直接插入排序
  • 原文地址:https://www.cnblogs.com/springxian/p/13651008.html
Copyright © 2011-2022 走看看