starjuly的专栏

记录JavaEE的学习笔记

Spring IOC注解方式

1、首先要导包
2、导入context名称空间
<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">


3、然后是xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<!-- 导入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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
       
<!-- applicationContext.xml启动扫描注解的配置 -->
          <context:component-scan base-package="star.july.d_annotation" ></context:component-scan>
</beans>

4、创建实体类并添加注解
User.java
package star.july.d_annotation;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("userID" //相当于:<bean id="userID" class="xxxx">
public class User {
          //注入地址
//       @Resource(name="addrID")  //  <property  ref="">
          //如果属性名称和需要注入的javabean的ID名称一致,可以使用@Autowired(可以省略setter方法)
          @Autowired
          private Address addr;
          public User() {
                   System.out.println("调用User构造方法");
          }
          
          
}

Address.java
package star.july.d_annotation;
import org.springframework.stereotype.Component;
@Component("addrID")
public class Address {
          public Address() {
                   System.out.println("调用address构造方法");
          }
          
}




5、测试
package star.july.d_annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo {
          public static void main(String[] args) {
                   ApplicationContext ac = new ClassPathXmlApplicationContext("star/july/d_annotation/applicationContext.xml");
                   ac.getBean("userID");
          }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/starjuly/article/details/52349067
文章标签: Spring IOC 注解
个人分类: JavaWeb
上一篇Spring 依赖注入(DI)
下一篇Spring JDBC整合
想对作者说点什么? 我来说一句

spring_Ioc

2017年08月07日 10KB 下载

没有更多推荐了,返回首页

关闭
关闭