spring学习笔记(一)-- Spring配置Bean __YIBAI

spring 理解

  1. IoC () :控制反转,当新建了一个java类,正常使用是在代码中使用 new 创建一个java对象实例,在spring中,使用配置文件来管理和创建 java对象(实例)。需要用到时,不需要使用 new 创建,而是通过spring 在容器中拿到一个对象
  2. DI ()依赖注入,在一个类中拥有另外一个类,或者说拥有另外一个类的属性,给这个属性赋值的过程我理解为依赖注入,在spring之前这个注入可以通过 seter 方法完成,spring中,依赖注入依然可以交给配置文件来完成。
    1. is a  是一个 → 继承
    2. has a 有一个 → 依赖(组合)
  • spring装配bean 

两种方式:

一:xml文件配置bean,xml文件配置,可以根据 类属性的类型(type),名字,构造方法自动装备bean

另外在类的属性(字段),构造方法,set方法上使用注解 @Autowired 也可以实现自动装备

@Autowired的使用:

使用 @Autowired ,需要注册 AutowiredAnnotationBeanPostProcessor。两种方式

① 配置文件中直接包含

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

② Include <context:annotation-config />

在配置文件头部添加

<beans 
	//...
	xmlns:context="http://www.springframework.org/schema/context"
	//...
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
	//...

	<context:annotation-config />
	//...
</beans>

二:javaConf配置bean : 使用java文件配置bean

测试实例:

一,创建项目 testIoC

测试点:从配置文件拿到bean(实体类)

package com.cn.entity;

public class User {
    private String userName ;

    public User() {
        // TODO 自動生成されたコンストラクター・スタブ
    }

    public User(String userName) {
        this.userName = userName;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

}

testIoC.xml

配置文件配置bean,需要bean保留无参构造函数,没有的话会报错【No default constructor found; nested exception is。。。】


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="userServices" class="com.cn.entity.User">
        <property name="userName" value="小明"/>
    </bean>

</beans>

TestGetBean.java


package com.cn.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cn.entity.User;

public class TestGetBean {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("testIoC.xml");
        User user = (User) context.getBean("userServices");
        System.out.println(user.getUserName());
    }
}

运行结果: 小明

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值