7.使用注解开发

使用注解开发

说明

  • 在Spring4之后,想要使用注解形式,必须得到引入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">
     
        <context:annotation-config/>
    </beans>

1.Bean实现

1)配置扫描那些包下的注解

<context:component-scan base-package="com.xiaoguan.pojo"/>

2)在指定包下编写类,增加注解

@Component("user")
//相当于配置文件中<bean id="user" class="..."/>
public class User{
    public String name = "xiaoguan";
}

3)测试

@Test
public void test(){
    ApplicationContext context = new ClassPathApplicationContext("bean.xml");
    User user = (User)context.getBean("user");
    System.out.println(user.name);
}

2.属性注入

使用注解注入属性

1)可以不用提供set()方法,直接在直接名上添加@value(“值”)

@Component("user")
public class User{
    @Value("xiaoguan")
    //相当于配置文件中<property name="name" value="xiaoguan"/>
    public String name;
}

2)如果提供了set方法,在set方法上添加@value(“值”);

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

3.衍生注解

@Component的三个衍生注解

  • @Controller:web层
  • @Service:service层
  • @Repository:dao层
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值