注解注入
xml文件配置属性的好处是可以把所有的配置都放在一起,方便后期修改,但是xml文件配置属性比较繁琐,而且需要两个文件直接切换,很是烦人。所以对于有些不经常修改甚至写完后不需要修改的bean
,使用注解配置是很好的选择。无论是注解配置还是xml文件配置,获取配置信息底层使用到的都是反射的技术。
环境搭建
- 导包:在Spring4中,使用注解需要再导入一个aop包。所以现在需要的包如下,网盘密码:t7hv。
- 导入约束:
<?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">
</beans>
注解开发入门
如果使用注解配置信息,必须再xml文件中配置一个扫描仪。这个扫描仪的作用的是当工厂加载xml文件后,告知Spring,哪些包下的类需要使用注解的方式来配置。
<context:component-scan base-package="com/spring/secondday" ></context:component-scan>
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/*
* @Component("userDao") 等价于 <bean id="userDao" class="com.spring.secondday.UserDaoImpl"></bean>
*/
@Component("userDao")
public class UserDaoImpl implements UserDao {
/* @Value设置值时不需要有setters方法。 */
@Value("HelloWorld")
private String name;
public void save() { }
public String toString() {
return "UserDaoImpl [name=" + name + "]";
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao ud = (UserDao)ac.getBean("userDao");
System.out.println(ud);
/*Console:
* UserDaoImpl [name=HelloWorld] */
}
}