spring学习笔记2

一、使用注解自动装配bean

1、注解使用步骤:

  • 先在applicationContext.xml 的头里面加上context约束
<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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
  •  在xml中添加注解的支持:
    <context:annotation-config/>

2、@Autowired 默认通过byType 的方式,如果有多个bean,则通过byName。

      当有多个name的时候,可以加上@Qualifier(value="XXX")来查找某个特定的。

3、@Resource 默认通过byName 的方式,如果找不到name,通过byType。如果两个都找不到,报错。两个都找不到的时候你也可以通过@Resource(name="XXX")来找。

二、使用注解

1、首先要有aop包,但是我们在用maven导入依赖时一般都是导入好了。

2、在applicationContext.xml里面加上扫描的范围

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

3、有注解的支持

<context:annotation-config/>

4、

4.1、在类名上 加上 @Component 表示就是一个bean。同时 @Component在不同的业务层有不同的写法。dao 层 @Repository、service层@Service、Controller层@Controller。

一般情况下xml和注解并存。不过也有完全在java类上使用注解开发的。

4.2、

pojo:

package com.eiji.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class USer {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Value("英二")
    public String name;

}

config:

package com.eiji.config;

import com.eiji.pojo.USer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.eiji")
public class Config1 {
    @Bean
    public USer getUser(){
        return  new USer();
    }
}

测试:

package com.eiji;

import com.eiji.config.Config1;
import com.eiji.pojo.USer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config1.class);
        USer getUser = (USer) context.getBean("getUser");
        System.out.println(getUser.name);
    }
}

pojo的类上写上@Component,表示这是一个bean。

在config的类上加上@Configuration表示这既是一个被spring管理的类,也表示这相当于一个applicationContext.xml,下面在加上@ComponentScan("com.eiji")表示扫描的范围。

最后测试是注意要用 AnnotationConfigApplicationContext来获取上下文。

*来自狂神spring的学习笔记

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值