spring使用注解开发

spring使用注解开发

使用注解开发必须引入aop的包.

在配置文件当中必须引入一个context约束.

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
</beans>

原始方式都是使用bean的标签进行bean注入,但是在实际开发中一般都会使用注解开发.

  • 配置扫描哪些包下的注解.
<!--指定注解扫描包-->
<context:component-scan base-package="com.kuang.pojo"/>
  • 在指定的包下编写类,增加注解.
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
    public String name = "秦疆";
}

测试:

@Test
public void test(){
    ApplicationContext applicationContext =new ClassPathXmlApplicationContext("beans.xml");
    User user = (User) applicationContext.getBean("user");
    System.out.println(user.name);
}

属性注入:
使用注解注入属性:
可以不用提供set方法,直接在属性名上添加@value("值")

@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
    @Value("秦疆")
    // 相当于配置文件中 <property name="name" value="秦疆"/>
    public String name;
}

如果提供了set方法,在set方法上添加@value("值"):

@Component("user")
public class User {
    public String name;
    @Value("秦疆")
    public void setName(String name) {
        this.name = name;
    }
}

备注:文章内容大都来自狂神笔记.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值