spring 使用注解开发

使用注解开发

使用注解必须导入content约束,必须保证aop的包导入

在这里插入图片描述

<?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">

    <context:annotation-config/>

</beans>

需要知道的几个注解:

  • @Component : 放在类上,相当于在注册了一个bean,@Component 组件
  • @Value:直接写在属性上,给属性赋值。他只能完成简单的属性赋值
  • @Component有几个衍生的注解,在web开发中,按照mvc三层架构分层
    • dao : @Repository
    • service :@Service
    • controller: @Controller
    • 这四个注解功能都是一样的,都代表在IOC(spring)容器中注册了一个bean
  • @Autowired : 可以在属性上直接用,也可以在set方法上面用。原理:是先通过byName的方法自动装配,如果找不到在通过byType方法。如果byName找不到的情况下,配置文件(applicationContent.xml)中又有多个类型,则会出错
  • @Qualifier:与@Autowired 配合使用,出现上面出错的情况下使用这个注解,这个相当于byName
  • @Resource:这个是java原生的注解 我感觉和@Autowired是差不多的
  • @Scope: 控制作用域的 singleton单例 prototype原型

测试

  • pojo中 user类
//相当于在注册了一个bean
//@Component 组件
@Component
public class User {
    @Value("小明")
    public String name;
}
  • applicationContent.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">

    <context:annotation-config/>
    <!-- 扫描包 这个包下面的注解生效-->
    <context:component-scan base-package="com.yxx.pojo"/>

</beans>
  • 测试
@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContent.xml");
    User user = (User) context.getBean("user");
    System.out.println(user);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值