注解注入自由度高,可以对部分类使用注解,也可以对所有类都使用注解。
下面代码是的Category使用xml定义java Bean, Product使用注解来定义java Bean
1、定义Catogory和Product
package com.how2j.pojo;
//这个类使用xml配置
public class Category {
private int id;
private String name;
//定义无参构造函数,如果提供了Set方法,则可以使用Set方法注入属性
public Category() {
}
//定义有参构造函数,可以使用构造方法来注入属性
public Category(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.how2j.pojo;
//这个类使用注解配置
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
//因为这个类没在xml文件中定义,所以使用注解来将这个类设置成java bean, 并设置id
@Component("p")
public class Product {
//普通属于类型
@Value("2")
private int id;
@Value("product test")
private String name;
//引用类型
//
@Resource(name="c")
private Category category;
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", category=" + category +
'}';
}
}
2、编写xml
注意:Product是使用注解进行定义java bean的,不在xml文件中,因此,spring必须开启组件扫描来找到Product的java bean,即指定spring的扫描包,下面的base-packag的值是需要扫描的包,即@Componet()所在目录
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 半注解方式:一个类在xml中定义,一个类使用注解定义-->
<!--开启组件扫描, 因为我们使用注解来注入属性,所以-->
<context:component-scan base-package="com.how2j.pojo"></context:component-scan>
<bean id="c" class="com.how2j.pojo.Category">
<constructor-arg name="id" value="1"/>
<constructor-arg name="name" value="category 1"/>
</bean>
</beans>
3、测试
package test;
import com.how2j.pojo.Category;
import com.how2j.pojo.Product;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
@Test
//spring的控制翻转
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" );
//这里的c是在定义xml文件中
Category c = (Category) context.getBean("c");
System.out.println(c);
}
@Test
//测试spring的属性注入
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" );
//这里的p是定义在类里的, 即@Component("p")
Product p = (Product) context.getBean("p");
System.out.println(p);
}
}
补充:目录结构如下: