栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring 使用注解开发

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring 使用注解开发

在Spring4之后 要使用注解开发 必须保证aop包导入了

使用注解需要导入context约束 增加 注解的支持




    
    

@Component:组件放在类上 说明这个类被Spring管理了 就是bean

import org.springframework.stereotype.Component;

//等价于
@Component
public class User {
    public String name = "xxx";
}

@Value

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//等价于
@Component
public class User {
    @Value("xxx")
//等价于
    public String name;
}


或者


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//等价于
@Component
public class User {
   
    public String name;
    @Value("xxx")
    public void setName(String name) {
        this.name = name;
    }
}

@Component有几个衍生的注解 我们在Web开发中会按照MVC三层架构分层
        ·dao[@Repository]
        ·service[@Service]
        ·controller[@Controller]
                这四个注解功能一样 都是代表将某个类注册到Spring中 装配Bean

 

 

注解的作用域 @Scope
        @Scope 放在类上,默认是单例模式
        @Scope(prototype)是原型模式,每次创建的都是一个新的对象

 其作用等价于

补充:
        @Scope("singleton") 或者  @Scope 单例模式  下面代码输出结果为true
        @Scope("prototype") 下面代码输出结果为false

import com.kero.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = context.getBean("user", User.class);
        User user2 = context.getBean("user", User.class);
        System.out.println(user==user2);
    }
}

xml vs 注解
        ·xml更加万能 适用于任何场合 维护简单方便
        ·注解 不是自己类使用不聊 维护相对复杂
最佳实践:xml用来管理bean 
                注解只负责完成属性的注入
                我们在使用的过程中 需要注意 使用以下代码               


    
    
    

                        
针对最佳实践的例子        





    
    
    

    



import org.springframework.beans.factory.annotation.Value;


public class User {
    @Value("XXX")
    public String name;
    public void setName(String name) {
        this.name = name;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/891740.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号