嗨,我是Spring的新手,现在我正在使用Maven运行我的应用程序
但是当我运行我的项目时,我会得到如下的异常
'一年' bean类[com.ensis.spring.MovieLister]:Bean属性'年'不可写或具有无效的setter方法。 setter的参数类型是否与getter的返回类型匹配?
public class Main {
public static void main(String[] args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
MovieLister movieLister = (MovieLister)ctx.getBean("lister");
movieLister.printMoviesByYear();
}
}
private int year;
private String name;
public Movie(int year, String name) {
super();
this.year = year;
this.name = name;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public class MovieFinder {
private static List<Movie>moviesList;
static{
moviesList.add(new Movie(1990, "A"));
moviesList.add(new Movie(1991, "B"));
moviesList.add(new Movie(1992, "C"));
moviesList.add(new Movie(1993, "D"));
moviesList.add(new Movie(1994, "E"));
moviesList.add(new Movie(1995, "F"));
}
public List<Movie>findMoviesByYear(int year){
List<Movie>findMovies=new ArrayList<Movie>();
for(Movie movie:moviesList){
if(year==movie.getYear()){
findMovies.add(movie);
}
}
return findMovies;
}
}
public class MovieLister {
private int year;
private MovieFinder movieFinder;
public void printMoviesByYear(){
List<Movie>found = movieFinder.findMoviesByYear(year);
for(Movie movie:found){
System.out.println("So movies are======>"+movie.getName());
}
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="lister" class ="com.ensis.spring.MovieLister" autowire="byType">
<property name="year" value="1991"/>
</bean>
<bean id="finder" class="com.ensis.spring.MovieFinder"/>
</beans>
答案 0 :(得分:0)
将一个setter添加到MovieLister:
public void setYear(final int year) {
this.year = year;
}
这是必需的,因为成员变量年份是私有的。
旁注: 如果MovieLister实例需要一年或任何其他成员变量,我强烈建议创建一个设置这些变量的构造函数。