关闭

Spring IOC注解方式

标签: SpringIOC注解
474人阅读 评论(0) 收藏 举报
分类:
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");
          }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:101250次
    • 积分:2261
    • 等级:
    • 排名:第18368名
    • 原创:122篇
    • 转载:0篇
    • 译文:0篇
    • 评论:33条
    文章分类
    最新评论