Spring之注解开发

本篇通过使用spring注解来创建自动装配bean

1、applicationContext.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--使用component-scan 扫描指定包下的Bean自动装配-->
    <context:component-scan base-package="com.lizheng.pojo"/>
    <!--注解生效配置-->
    <context:annotation-config/>
</beans>

【注意】    <context:component-scan base-package="com.lizheng.pojo"/> 

<!--注解生效配置--> <context:annotation-config/> 

2、添加@Component注解,表示<context:component-scan base-package="com.lizheng.pojo"/>会扫描到包下的有@Component注解的所有类,创建和装配到spring,属性值注入则是通过@Value,【注意】这里@Value是导入import org.springframework.beans.factory.annotation.Value;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Data
@Component
@Scope("singleton")
public class User {
    //属性值注入通过@value
    @Value("rourou")
    public String name;
}

3、测试类

public class MyTest {

    @Test
    public void myTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = context.getBean("user", User.class);
        User user1 = context.getBean("user", User.class);
        System.out.println(user.hashCode());
        System.out.println(user1.hashCode());
        System.out.println(user==user1);
    }
}

【拓展】

@Component注解有几个衍生注解,在web开发中,根据MVC三层架构分为

1、dao[@Repository]

2、service[@Service]

3、controller[@Controller]

这四个注解的功能是一样的,都是代表讲某个类注册到spring中,装配bean

【注意】当某类中不仅有基础数量类型变量,还有引用类型变量时,则要使用@Autowired

另外要注入依赖中导入aop的jar包

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值