【Spring】注解开发
程序员文章站
2022-03-05 12:04:23
...
使用注解须知:
1.导入约束
2.配置注解的支持
<?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/>
</beans>
注解实现自动装配:
package com.lixin.pojo;
public class Cat {
public void shout(){
System.out.println("喵喵!");
}
}
------------------------------------------------------------
package com.lixin.pojo;
public class Dog {
public void shout(){
System.out.println("汪汪!");
}
}
--------------------------------------------------------------
import org.springframework.beans.factory.annotation.Autowired;
public class People {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public Dog getDog() {
return dog;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
-------------------------------------------------------------------------
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="cra" class="com.lixin.pojo.Cat"/>
<bean id="dog" class="com.lixin.pojo.Dog"/>
<bean id="people" class="com.lixin.pojo.People"/>
<context:annotation-config/>
</beans>
-----------------------------------------------------------------------------
import com.lixin.pojo.People;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext
("ApplicationContext.xml");
People people=context.getBean("people",People.class);
people.getDog().shout();
people.getCat().shout();
}
}
@Autowired
直接在属性上使用即可!也可以在set上使用
使用Autowired我们可以不用编写set方法,前提是这个自动装配的属性在IOC容器中存在且符合名字byName!
上一篇: JS监听回车事件
下一篇: react监听回车事件