1spring的bean管理---通过注解方式
a:注解
代码里面特殊标记,使用注解可以完成功能;
注解写法:@注解名称(属性名称=属性值)
注解可以用在类、方法、属性上面做出功能
2spring注解开发准备
a:导入jar包
导入基本的jar包;
导入aop的jar包
b:创建类,创建方法
c:创建spring配置文件,引入约束
做ioc基本功能,引入约束beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
做ioc注解开发,需要引入新的约束
http://www.springframework.org/schema/context/spring-context-4.2.xsd
d:开启注解扫描的配置
(到包里面扫面类、方法、属性上面是否有注解)base-package="创建对象所在类的包的全路径"
<context:component-scan base-package="com.sun.anno"></context:component-scan>
扫面属性上面的注解
<context:annotation-config></context:annotation-config>
3注创建对象
写在类的上面:@Component(value="user")//value的值相当于配置方式中的id值
eg:
User.java
@Component(value = "user")//相当于配置文件中的<bean id="" class=""></bean>id的值 public class User { public void add(){ System.out.println("add...."); } }
TestUser.java
public class TestAnno { @Test public void testUser(){ //1加载spring配置文件,根据创建对象 ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); //2得到注解创建的对象 User user = (User) context.getBean("user"); user.add(); } }
注意:Spring中提供@Component的三个衍生注解
@Controller:web层
@Service:业务层
@Repository:持久层
创建对象单实例还是多实例
@Scope(value="prototype")//多实例
@Scope(value="Singleton")//单实例
4注解注入属性
a:创建service类,创建dao类,在service得到dao对象
@Autowired
@Resource(name="注入对象的名字")
UserService.java
@Service(value = "userService") public class UserService { //得到dao对象 //1定义dao类属性 //在dao属性上面使用注解,完成对象注入 @Autowired//相当于@Resource(name="userDao")//name属性写注解创建dao对象value值 private UserDao userDao; //使用注解方式不要set方法 public void add(){ System.out.println("service...."); userDao.add(); } }
UserDao.java
@Component(value = "userDao") public class UserDao { public void add(){ System.out.println("dao...."); } }
TestUser.java
@Test public void testService(){ //1加载spring配置文件,根据创建对象 ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); //2得到注解创建的对象 UserService userService = (UserService) context.getBean("userService"); userService.add(); }