1.在beans中配置context标签,使其能使用注解
<context:component-scan base-package="com.lixv.entity"/>
<context:annotation-config/>
- context:component-scan用于扫描这个包下的注解
- context:annotation-config用于注解的支持
2.@Component注解
package com.lixv.entity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
public class Dog {
private String name;
public void shut(){
System.out.println("狗在叫");
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
'}';
}
}
- @Component注解将这个类添加到beans中,成为一个bean。
- 相当于
<bean id="dog" class="com.lixv.entity.Dog/>"
3.@Value注解
package com.lixv.entity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
public class Dog {
@Value("kkkkk")
private String name;
public void shut(){
System.out.println("狗在叫");
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
'}';
}
}
- @Value注解给属性赋值。
- 加上如上所示的@Value注解,相当于
<bean id="dog" class="com.lixv.entity.Dog">
<property name="name" value="kkkkk"/>
</bean>
4.@Scope注解
package com.lixv.entity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("singleton")
public class Dog {
@Value("kkkkk")
private String name;
public void shut(){
System.out.println("狗在叫");
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
'}';
}
}
- 加上@Scope注解,相当于
<bean id="dog" class="com.lixv.entity.Dog" scope="singleton">
<property name="name" value="kkkkk"/>
</bean>