必须导入aop包
还得要引入一个context约束
package demo2.com.sicheng.entity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.List; @Component("江喆傻逼") public class Hello { @Value("NMSL") private String name; @Autowired private List<Person> person; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Person> getPerson() { return person; } public void setPerson(List<Person> person) { this.person = person; } public Hello(String name, List<Person> person) { this.name = name; this.person = person; } public Hello() { } @Override public String toString() { return "Hello{" + "name=‘" + name + ‘\‘‘ + ", person=" + person + ‘}‘; } }
package demo2.com.sicheng.entity; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("确实") public class Person { @Value("123") private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(int age) { this.age = age; } public Person() { } @Override public String toString() { return "Person{" + "age=" + age + ‘}‘; } }
<?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"> <context:annotation-config/> <context:component-scan base-package="demo2.com.sicheng.entity"/> </beans>
import demo2.com.sicheng.entity.Hello; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { @Test public void HelloTest(){ ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); Hello hello = (Hello)context.getBean("江喆傻逼"); System.out.println(hello.toString()); } }
对于@Component注解:
原文:https://www.cnblogs.com/sicheng-li/p/13156408.html