Spring笔记

发布时间 2023-03-22 21:15:45作者: KxWanna

spring

1.创建项目

GroupID是项目组织唯一的标识符, 比如我的项目叫test001  那么GroupID应该是 com.lixiaoming.test001 域名.公司名.项目名
ArtifactID就是项目的唯一的标识符, 一般是 项目名-xxx   比如test001-model

2.配置文件

开启自动装配
< context:annotation-config/>
指定要扫描的包,这个包下面的注解才会生效
<context:component-scan base-package="xxx.xxx"/>

有了< context:component-scan>,另一个< context:annotation-config/>标签可以移除掉,因为已经被包含进去了。

3注解

3.1@AutoWired

默认是byType方式,如果匹配不上,就会byName

public class People {
    @Autowired
    private Cat cat;
}

3.2@Nullable

字段标记了这个注解,说明该字段可以为空

public name(@Nullable String name){}

3.3@Autowired+@Qualifier

@Autowired不能唯一装配时,需要@Autowired+@Qualifier

public class People {
    @Autowired
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog")
    private Dog dog;
    private String name;
}

3.4@Resource

默认是byName方式,如果匹配不上,就会byType

public class People {
    Resource(name="cat")
    private Cat cat;
    Resource(name="dog")
    private Dog dog;
    private String name;
}

@Resource和@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired通过byType的方式实现,而且必须要求这个对象存在【常用】
  • @Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】
  • 执行顺序不同:@Autowired通过byType的方式实现。@Resource默认通过byname的方式实现

3.5@Component

等价于<bean id="user" classs"pojo.User"/>

@Component
public class User {  
     public String name ="秦疆";
}

@Component有几个衍生注解,会按照web开发中,mvc架构中分层。

  • dao (@Repository)
  • service(@Service)
  • controller(@Controller)
    这四个注解的功能是一样的,都是代表将某个类注册到容器中

4作用域

//原型模式prototype,单例模式singleton(sping默认)
//scope("prototype")相当于<bean scope="prototype"></bean>
@Component 
@scope("prototype")
public class User { 
    
    //相当于<property name="name" value="kuangshen"/> 
    @value("kuangshen") 
    public String name; 
    
    //也可以放在set方法上面
    @value("kuangshen")
    public void setName(String name) { 
        this.name = name; 
    }
}