ではパートIは、使用し@Autowired
開発を簡素化するために、実際にも簡素化することができます:
パートI、xml
指定されたクラス構成を、次のように:
<bean id="address" class="com.weizu.pojo.UserAddress" p:address="西安"/>
<bean id="weizu" class="com.weizu.pojo.User" p:name="张三">
<property name="age" value="21"></property>
</bean>
1. @ Component
現時点では、必要ありません。component
注釈スキャンのアドレスを直接指定するために使用します。今回は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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置注解扫描。 指定要扫描的包,这个包下的注解就会生效 -->
<context:component-scan base-package="com.weizu.pojo"/>
<context:annotation-config/>
</beans>
その後、指定にUser.java
し、UserAddress.java
@Component
package com.weizu.pojo;
import org.springframework.stereotype.Component;
/**
* @Component等价于
* <bean id="address" class="com.weizu.pojo.UserAddress" p:address="西安"/>
*/
@Component
public class UserAddress {
public String address = "西安";
@Override
public String toString() {
return "UserAddress{" +
"address='" + address + '\'' +
'}';
}
}
package com.weizu.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class User {
public int age = 12;
public String name = "张三";
@Autowired
private UserAddress address;
@Override
public String toString() {
return "User{" +
"age=" + age +
", name='" + name + '\'' +
", address=" + address +
'}';
}
}
次に、テストします。
public class myTest {
@Test
public void Test(){
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 此时在beans.xml中没有指定id,由于@Component是其等价写法,默认的id也就是类的名字的小写
User userService = (User) context.getBean("user");
System.out.println(userService.toString());
}
}
でbeans.xml
指定さid
れておらず@Component
、同等であるため、デフォルトid
はクラス名の小文字であり、ここに記述されていますuser
。クラスに配置されたものを
使用@Component
して、このクラスがSpring
管理されていることを示しbean
ます。つまり、です。
2. @ Value
使用@Value
は、属性の値を指定したり、定義された位置に配置したり、set
メソッドに配置したりすることができます。以下のためにUser
クラスとして、次のとおりです。
@Component
public class User {
@Value("14")
private int age;
@Value("张三")
private String name;
@Autowired
private UserAddress address;
@Override
public String toString() {
return "User{" +
"age=" + age +
", name='" + name + '\'' +
", address=" + address +
'}';
}
}
効果は同じままです:
それらの間で@Value("14")
、それは同等です<property name="age" value="14"></property>