autowire가 코멘트

원본 링크 : https://www.mk2048.com/blog/blog.php?id=h020bic22jab&title=Autowired%E6%B3%A8%E8%A7%A3
package com.how2java.pojo;
 
import org.springframework.beans.factory.annotation.Autowired;
 
public class Product {
 
    private int id;
    private String name;
    @Autowired
// 等价于 @Resource(name="c")
private Category category; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } // @Autowired public void setCategory(Category category) { this.category = category; } }
--------------------Category类-----------------

패키지 com.how2java.pojo;

공용 클래스 카테고리 {

공공 INT getId () {
반환 아이디;
}
공개 무효 setId (INT 아이디) {
this.id = ID;
}
공공 문자열 getName () {
반환 이름;
}
공공 무효에서는 setName (문자열 이름) {
this.name = 이름;
}
개인 INT 아이디;
개인 문자열 이름;
}

--------------------------
<?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">
  
    <context:annotation-config/>  //使用注解
    <bean name="c" class="com.how2java.pojo.Category">
        <property name="name" value="category 1" />
    </bean>
    <bean name="p" class="com.how2java.pojo.Product">
        <property name="name" value="product1" />
<!--         <property name="category" ref="c" /> --> //已经注解     @Resource
    </bean>
  
</beans>

-----------------------

패키지 com.how2java.test;

수입 org.springframework.context.ApplicationContext;
수입 org.springframework.context.support.ClassPathXmlApplicationContext;

수입 com.how2java.pojo.Product;

공용 클래스 TestSpring {

공공 정적 무효 메인 (문자열 []에 args) {
ApplicationContext의 컨텍스트 = 새로운 ClassPathXmlApplicationContext (새로운 String [] { "applicationContext.xml"});
제품 P = (제품) context.getBean ( "P");
에서 System.out.println (p.getName ());
에서 System.out.println (p.getCategory () getName ().);
}
}


보다 전문적인 프런트 엔드 지식의 확인 [2048] 원숭이 www.mk2048.com을

추천

출처blog.csdn.net/weixin_39037804/article/details/102756144