开启注解支持
使用注解需要在配置文件applicationContext.xml中开启注解支持,并扫描注解所在的包以保证能被识别。
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解支持-->
<context:annotation-config/>
<!--指定要扫描的包-->
<context:component-scan base-package="com.pojo"/>
</beans>
Bean注解
主要分为以下四种:
- @Component(在任意层使用)
- @Repository(在dao层使用)
- @Service(在service层使用)
- @Controller(在controller层使用)
这四种注解本质上都是一样的,实现相同的功能,但是为了更好地理解代码,方便一眼了解代码的功能,一般会进行区分。
注解简单使用
@Component
@Scope("prototype")//用来表示作用域
public class User {
@Value("张三")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
说明:
- @Scope(“singleton”)表示作用域为单例模式,即每次从Spring容器中取到的对象都是同一个
- @Scope(“prototype”)表示作用域为原型,即每次从Spring容器中取到的对象是不同的
测试
import com.pojo.People;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {
@Test
public void test(){
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user", User.class);
System.out.println(user.getName());
}
}