zoukankan      html  css  js  c++  java
  • Spring-使用注解开发(十二)

    1.使用注解开发需要导入spring的一系列包;

    2.需要再配置文件中加一个约束:context;

    xmlns:context="http://www.springframework.org/schema/context"
    http://www.springframework.org/schema/context  https://www.springframework.org/schema/context/spring-context.xsd

    3.配置扫描组件

         <!--自动扫描包下的注解-->
        <context:component-scan base-package="org.west.pojo"/>

    4.编写代码

    package org.west.pojo;
    
    import org.springframework.stereotype.Controller;
    
    @Controller("stu")
    public class Student {
    
        public String name="喜洋洋";
    
    }

    5.测试

    public class testor {
    
        @Test
        public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            Student stu = (Student) context.getBean("stu");
            System.out.println(stu.name);
        }
    }

    IOC注入

    1.可以不用提供set方法,可以直接在属性名上添加一个@Values(值);

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    
    @Controller("stu2")
    public class Student {
         @Value("灰太狼")
        private String name;
    
        public String getName() {
            return name;
        }
    
    }

    这样也可以吧值注入进去.

    2.有set方法可以直接在set方法上面加上@Values(值)也可以吧值注入进去

    @Controller("stu2")
    public class Student {
    
        private String name;
    
        public String getName() {
            return name;
        }
        @Value("灰太狼")
        public void setName(String name) {
            this.name = name;
        }
    }

    注解和XML对比

    • xml可以适用于任何场景,结构清晰。

    • 注解不是自己提供的类,存在局限性;好处:开发简单,方便

  • 相关阅读:
    CVE-2019-16097:Harbor任意管理员注册漏洞复现
    wfi破解
    Phpstudy隐藏后门
    远程桌面--------ms12-020 漏洞复现 (死亡蓝屏)
    心脏滴血漏洞复现(CVE-2014-0160)
    疑难杂症----克隆虚拟机无法上网
    疑难杂症----Windows10
    mono修改代码模板
    mono for android 各版本下载地址(目前没多大参考价值了,老文章了)
    单独安装VS2012装mono for android
  • 原文地址:https://www.cnblogs.com/xiaoqiqistudy/p/11312040.html
Copyright © 2011-2022 走看看