javaweb中spring的注解

spring中的注解概念的引入
因为 bean的数量过多, 所以spring的配置文件可能会非常大,不利于管理和维护,随着jdk5的
注解功能的诞生,spring也开始兼容注解 功能! 注解功能的实现提高spring.xml配置的代码维护! 自动加载 spring.xml的bean类, 当Demo测试类 运行时 , spring框架会 自动的注入到程序中, 在 程序中通过调用接口,接口调用实现类,实现类中有相关的注解,通过 个 实现类的相关的注解,就可以达到简化spring.xml的效果了

***常用的注解:
@Component
可以使用它描述 spring 的bean ,但是它 是一个泛化的概念,表示一个组件,可以作用在任何的 层次上,使用时 将该注解标注在相应的类上。
@Service
通常作用在 业务层,用于将业务层的类标识为spring中的bean ,功能与@ Component相同。
@Controller
通常作用与控制层,用于将控制层的类标识为spring中的bean ,功能与@ Component相同。
@ Autowired
用于对bean的属性变量属性的set方法及构造函数进行标注,配合对应的注解处理器 完成bean的自动装配工作,默认是按照bean 的类型进行装配的
@ Resource
作用与@ Autowired一样, 区别是@ Autowired默认是按照Bean的类型来装配的,而@ Resource默认是按照bean的实例名称进行装配的。


1:创建接口

package com.annotation;
public interface PersonDao {
	public void add();

}


package com.annotation;
public interface PersonService {
	public void add();
}

2:完成接口实现类(并在实现类中添加相应的注解, 以便后面配置spring.xml
时,更加简化)

package com.annotation;
import org.springframework.stereotype.Component;
@Component
public class PersonDaoImpl implements PersonDao {
	@Override
	public void add() {
		// TODO 自动生成的方法存根
		System.out.println("dao的add执行");
	}
}



package com.annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
//为创建personDao 
public class PersonServiceImpl implements PersonService {
	@Autowired //为getPersonDao
	
	private PersonDao personDao;

	public PersonDao getPersonDao(){
		return personDao;
	}

	@Override
	public void add() {
		// TODO 自动生成的方法存根
		personDao.add();
		System.out.println("service的add执行!");
	}

}





3:spring.xml的配置!

   
    <!--自动的扫描包下的 文件,通过注解的方式可以让xml配置文件简化! -->
    <context:component-scan  base-package="com.annotation"/>

4测试类的创建!

package com.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo {
	public static void main(String[] args) {
		// 加载xml配置文件,有了这条语句,当程序运行时 ,spring会根据xml自动为程序加载需要的bean。
		String xmlPath = "spring.xml";
		// 实例化和初始化这个ApplicationContext,构建spirngioc容器。
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);

		// ioc 通过getBean()方法,创建对象!
		PersonAction personAction = (PersonAction) applicationContext.getBean("personAction");

		// 调用add( )方法。
		personAction.add();

	}

}

5:运行结果:

在这里插入图片描述

发布了80 篇原创文章 · 获赞 15 · 访问量 1869

猜你喜欢

转载自blog.csdn.net/weixin_43319279/article/details/103120158