一、Spring的基本配置

1.创建maven项目

pom.xml中导入Spring依赖

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.13</version>
        </dependency>

2.创建实体类

package com.yy.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Goods {
    private String goodID;
    private String goodName;
    private String goodType;
    //品牌ID
    private String brandID;
    private BigDecimal cost;
    private String providerID;
    
    public Goods(String goodID, String goodName) {
        this.goodID = goodID;
        this.goodName = goodName;
    }
}

3.配置文件

在resource文件夹下新建ApplicationContext.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="goods" class="com.yy.pojo.Goods">
        <property name="goodName" value="主板"></property>
    </bean>

</beans>
  • bean:通过配置bean将实体类对象交给Spring容器
  • id:给被管理的对象命名
  • class:被管理对象的全限定名
  • scope(进阶):默认singleton即为单利模式,就是在Spring容器中只存在一个的实例。
  • property:通过Set方法进行依赖注入
  • 依赖注入常用的两种:1.set方法注入。2.构造函数注入。
  • 另外两种(了解)p命名和c命名空间注入:不能直接使用,需导入xml约束。
<bean id="goods" class="com.yy.pojo.Goods">
<!--        <property name="goodName" value="主板"></property>-->
        <constructor-arg name="goodID" value="z001"></constructor-arg>
        <constructor-arg name="goodName" value="主板"></constructor-arg>
    </bean>

4.测试类

import com.yy.pojo.Goods;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class yyTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("AplicationContext.xml");
        Goods goods = (Goods) context.getBean("goods");
        System.out.println(goods.getGoodName());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值