需求:
bean对象本身,移出beans.xml配置文件,也通过注解进行。
创建文件:
同注入对象章节。
1.创建com.tutorialspoint包
2.创建HelloWorld类
3.创建MainAPP主类(void main)
4.创建Beans.xml
5.ModelTest类
代码:
Beans
删掉之前留下的代码,新增<context:component-scan base-package="com.tutorialspoint"/>
其作用是告诉Spring,bean都放在com.tutorialspoint这个包下
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.tutorialspoint"/>
</beans>
HelloWorld.java
为HelloWorld类加上@Component注解,即表明此类是bean,name为helloworld。
package com.tutorialspoint;
import org.springframework.stereotype.Component;
@Component("helloworld")
public class HelloWorld {
private String message = "helloworld";
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
ModelTest.java
为ModelTest类加上@Component注解,即表明此类是bean,name为modeltest。
@Autowired保留。
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("modeltest")
public class ModelTest {
private String str = "modeltest";
@Autowired
private HelloWorld helloWorld;
public void setStr(String string){
this.str = string;
}
public void getStr(){
System.out.println("Your str : " + str);
}
public void setHelloWorld(HelloWorld helloworld){
this.helloWorld = helloworld;
}
public void getHelloWorld(){
helloWorld.getMessage();
}
}
MainApp.java
保留不变,和原来一样。
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloworld");
obj.getMessage();
ModelTest model = (ModelTest) context.getBean("modeltest");
model.getStr();
model.getHelloWorld();
}
}
运行结果:
要点:
@component一般用来配置