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

Spring注解

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

Spring注解

使用注需要配置注解的支持

applicationContext.xml



    
     
    
    
    
    
    


pom.xml



    org.springframework
    spring-webmvc
    5.3.19



    org.springframework
    spring-jdbc
    5.3.19

@Autowired

bean文件按上方配置,然后在属性上面写注解,就可以实现自动装配

@Qualifier通过id指定bean进行装配



当@Autowired自动装配比较复杂时可以使用@Qualifier组合装配

@Resource注解
public class People {

    private String name;
    @Resource
    private Cat cat;
    @Resource(name="dog3")
    private Dog dog;
}
@Resource注解和@Autowired的区别
  • 都是用来自动装配的,都可以放在属性字段上面
  • @Autowired通过byType 的方式实现,而且逼需要求这个对象存在【常用】
  • @Resource默认是通过byName的方式来实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下会报错【常用】
  • 执行顺序不同@Autowired通过byType的方式实现。@Resource默认通过byName的方式实现.
@Component

等价于


@Value("值")

等价于:


    

@Repository

在dao层使用

@Controller

在controller层使用

@Service

在service层使用

通过纯java的方式也可以实现

PengConfig类.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import peng.pojo.User;

@Configuration
public class PengConfig {
    @Bean
    public User getUser(){
        return new User();
    }
}

实体类User

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

@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }
    @Value("鹏哥")
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + ''' +
                '}';
    }
}

测试类

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import peng.controller.PengConfig;
import peng.pojo.User;

public class MyTest {
    public static void main(String[] args) {
       ApplicationContext context = new AnnotationConfigApplicationContext(PengConfig.class);
       //这里的对象跟Spring的对象不一样
        User user= (User) context.getBean("getUser");
        System.out.println(user.getName());
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/886326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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