【SSM-Spring】Spring IOC

1在src下创建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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context     
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
在这配置bean
<bean name=" bean的名字在 后面创建对象时调用 "  class= "com. 包到 类名" >
    	<property name="类.属性名" value=“预设值”>
  < bean>
    </beans>

2.Test.java

package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.how2java.pojo.Category;
import com.how2java.pojo.Pro;
public class Test {
	public static void main(String[] args) {
	     ApplicationContext context = new ClassPathXmlApplicationContext(
	    		 new String[] { "applicationContext.xml" }); 
	    		   Category cc=(Category)context.getBean("c");
     System.out.println(cc.getName());
     
    Pro p = (Pro)context.getBean("p");
     
    System.out.println(p.getName());
    System.out.println(p.getCate().getName());
	
	}	
}

3.注解 简化applicationcontext.xml

3.1@Autowired

  <context:annotation-config/>

可以把类中 的类对象 引用 去掉
在引用的类中 的声明 或者 set方法上 @Autowired,让其自动找到注入对象的类
等同在

<bean>
<property name="" ref=" bean.name">
</bean>
        @Autowired
        private Category category;
      // 或者
        @Autowired
        public void setCategory(Category category) {
            this.category = category;
        }

**3.2@Resource

把 类对象 指向了在applicationcontext.xml中的bean 类

   @Resource(name="c")
    private Category category;

3.3 @Component 更近一步
把applicationcontext.xml 中的除了 beans标签外的内容全部去掉
只需要一句

<context:component-scan base-package= "com. 包到 类名" />

然后在类的上面 @Component(" name ") 你想给类起的名字
就可以直接在实例中context.getBean(“name”) 调用,不过之前在bean中给设置的值没了哦,得在定义类中重新设置。
@Component(“p”)
public class Product {

private int id;
private String name="product 1";
 
@Autowired
private Category category;


@Component("c")
public class Category {

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值