Photography theory: a beginner's guide(telegraph.co.uk)

本文精选了六本摄影领域的经典著作,包括《决定性瞬间》、《论摄影》等,并提炼了每本书的核心观点,旨在为读者提供一个快速了解摄影理论的途径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Have you read the Bible cover to cover? Probably not, but it's also fair to assume you know the basic plot, the central characters and a few choice quotes. This is the point Pierre Bayard makes in his mischievously titled book How to Talk About Books You Haven't Read, which is less a beginner's guide and more a study of different degrees of familiarity. Some books you may have read and reread, he points out, and genuinely know by heart; others skimmed and got the gist of. Some you may have heard so much about from others that you can bluff convincingly in conversation.

There are many such books in photography, referenced and re-referenced so often they're almost an article of faith. We polled our Twitter followers to find out which of these books you consider necessary reading. The results are below, but we'd love to hear if you have other titles we should consider. Maybe you know these texts backwards – but maybe you've read and forgotten them, or never actually taken them on. If the latter, these guides may serve as a refresher, or as pointers to see you on your way. You never know, they may even inspire you to crack open the covers yourself. Diane Smyth

The Decisive Moment by Henri Cartier-Bresson (1952), digested by Rachel Segal Hamilton

What's it about?

"The decisive moment", an idea that has defined street photography and photojournalism as we know it, was first outlined in the preface to a book of photographs by Henri Cartier-Bresson. The essay starts with Cartier-Bresson charting his life so far as a photographer – from messing around with a Box Brownie as a child to co-founding Magnum Photos – before talking through his approach to photography.

According to Cartier-Bresson, there is an almost magical split-second in which events in the world – interactions between people, movement, light and form – combine in perfect visual harmony. Once it passes, it is gone forever. To capture such moments as a photographer you must be inconspicuous, nimble and attentive; working on instinct; responding to reality and never trying to manipulate it.

Composition cannot be planned, nor can it be added in afterwards. Cropping will invariably make a good shot worse and is unlikely to make a bad shot better. Camera settings shouldn't be something the photographer even thinks about – taking a photograph should be like changing gears in a car.

In his own words:

“We photographers deal in things that are constantly vanishing, and when they have vanished, there is no contrivance on earth which can bring them back again.”

“Composition must be one of our constant preoccupations, but at the moment of shooting it can stem only from our intuition, for we are out to capture the fugitive moment, and all the interrelationships involved are on the move.”

“To me, photography is the simultaneous recognition in a fraction of a second, of the significance of an event as well as of a precise organisation of forms which give that event its proper expression.”

How to sound as if you've read it:

Be ready and reactive. Don't get hung up on kit and, most importantly, keep it real.

 

On Photography by Susan Sontag (1977), digested by Rachel Segal Hamilton

What's it about?

According to Sontag, photographs turn the world into a set of collectible objects that we can own. This makes us feel knowledgeable, and powerful. But although we still treat photos as evidence, photographers never simply record the world, they interpret it. They might take multiple shots, for example, selecting the ones that meet their preconceptions.

This is true for us non-professsionals, too: we use family albums to connect with the past and take holiday snaps to show our friends what we're up to. Bit by bit, though, photography has started to limit our experience. Instead of photographing what we're doing, we do things so that we can photograph them.

There is a moral dimension to Sontag's critique. By photographing a situation, you can't intervene in it – war photography is horrific, she says, partly because of the way it has become acceptable for a photographer to choose to take a photo rather than to save a life. But images also numb us. The more photographs of suffering we see, the less shocked we are. For Sontag, there is a violence to photography. The camera is predatory because it lets the photographer turn people into objects and to know them in a way they cannot know themselves.

We try to use photography to make sense of reality but the knowledge it gives us will always be sentimental, superficial, never political. To make matters worse, we're hooked. We don't feel we have really experienced something unless we've photographed it. And so we photograph everything.

In her own words:

“To photograph people is to violate them, by seeing them as they never see themselves, by having knowledge of them they can never have; it turns people into objects that can be symbolically posessed.”

“In these last decades 'concerned' photography has done at least as much to deaden our conscience as to arouse it.”

“Today everything exists to end in a photograph.”

How to sound as if you've read it:

People these days feel the need to photograph everything - it's totally ruining our experience of life.

Regarding the Pain of Others by Susan Sontag (2003), digested by Diane Smyth

This was Sontag's update to On Photography (see above). The intervening years hadn’t softened her stance and Sontag pulls no punches in her critique of images of suffering, “those professional, specialised tourists known as journalists” who make them, and our culpability in looking at them.

She starts by tracing the history of images of suffering, arguing that Christian depictions of martyrdom historically gave way to something more secular that saw pain as something to be deplored. Photographs were quickly pressed into service; justified by the idea they could advocate for change.

Photographs were, and still are, she argues, unequal to the task, because they turn disaster into universal, ineffectual denunciations of human cruelty or suffering. Each image is framed by the person who makes it, and “to frame is to exclude”.

Feeling powerless to change what they see, viewers quickly become immune to images of suffering or - worse - take a prurient interest in them. And because we are bombarded with such images, we no longer recognise them as records of real events.

It’s gloomy reading for committed photojournalists and Sontag has little to offer by way of comfort, other than to suggest that narrative texts, longer portfolios of images, and artworks are more likely to mobilise a viewer (or reader) to action against suffering, or any kind of understanding of it.

In her own words:

"Being a spectator of calamities taking place in another country is a quintessential modern experience, the cumulative offering by more than a century and a half’s worth of those professional, specialised tourists known as journalists. Wars are now also living room sights and sounds. Information about what is happening elsewhere, called ‘news’, features conflict and violence…to which the response is compassion, or indignation, or titillation, or approval, as each misery heaves into view."

"The photographer’s intentions do not determine the meaning of the photograph, which will have its own career, blown by the whims and loyalties of the diverse communities that have use for it."

"Making suffering loom larger, by globalising it, may spur people to feel they ought to ‘care’ more. It also invites them to feel that the sufferings and misfortunes are too vast, too irrevocable, too epic to be much changed by any local political intervention."

How to sound as if you've read it:

Photographs of suffering don't rouse viewers to action because they universalise pain rather than explaining what could be changed. There’s no hope, so stop being a voyeur and take action instead.

The Work of Art in the Age of Mechanical Reproduction by Walter Benjamin (1936), digested by Lewis Bush

What's it about?

Walter Benjamin was a German-Jewish critic and essayist. In his lifetime he was relatively unappreciated but since his suicide in 1940 he has been reappraised as one of the 20th century’s most important writers. Published in 1936 and originally aimed at a small group of Marxist intellectuals this essay has rather surprisingly become Benjamin’s best known, partly helped by its prominence in John Berger’s influential 1972 television series Ways of Seeing.

Benjamin packs a remarkably wide ranging discussion into a relatively short space, but a key concept is the idea that unique works of art such as paintings possess an "aura" that copies and reproductions like photographs do not. Even though works of art have always been reproducible, whether by hand or through semi-mechanical processes such as stamping, modern forms of reproduction such as photography represent something new, allowing the artwork to be seen in very different contexts to the original, potentially changing how the work of art is understood.

For photography this essay is significant in two main respects. Firstly because it explores the belief that photographs are inferior to traditional forms of art such as painting. Secondly because it’s a very specific example of the way the context of a photograph alters the way a viewer understands the thing that it shows.

In his own words:

"Objects made by humans could always be copied by humans….but the technological reproduction of artworks is something new."

"In even the most perfect reproduction, one thing is lacking: the here and now of the work of art, its unique existence in a particular place. It is this unique existence and nothing else that bears the mark of the history to which the work has been subject."

"What withers in the age of mechanical reproduction is the aura of the work of art."

How to sound as if you've read it:

The infinitely reproducible photograph lacks the aura of the unique work of art.

 

'Photographs of Agony' by John Berger (1972), digested by Rachel Segal Hamilton

What's it about?

How much photojournalism can change things for the better is subject to ongoing debate. One of the earlier writers to raise the issue was John Berger in this essay, first published in New Society magazine. Referring to a Don McCullin photograph of a wounded Vietnamese man and child, Berger considers why it has lately become acceptable to publish such graphic images.

He gives two reasons. First, that newspapers are responding to readers who want to see the truth. Second, that readers have have become desensitised to these images and newspapers are publishing ever more shocking pictures to win their attention. Dismissing both explanations, Berger suggests a third: that these photographs can be published precisely because they don't make viewers question who might be responsible for the violence. If they did then papers – in thrall, he says, to the political establishment – wouldn't publish them.

So what effect do they have? McCullin's images often capture moments in which time suddenly seems to pause – the instant a person cries out in grief, say. For viewers, time is similarly interrupted as we are, briefly, overcome with the victim's pain. But we mistakenly interpret this interruption as our own moral failure because we can't respond directly. We either think, "Well, what can I do?" and do nothing, or try to assuage our guilt by donating to charity. War photographs don't lead us to query the political systems under which wars take place – they just make war seem like some awful but inevitable feature of human life.

In his own words:

"[Photographs of agony] bring us up short. The most literal adjective that could be applied to them is arresting. We are seized by them.”

“The reader who has been arrested by the photograph may tend to feel this discontinuity as his own moral inadequacy. And as soon as this happens even his sense of shock is dispersed: his own moral inadequacy may now shock him as much as the crimes being committed in the war.”

“What we are shown horrifies us. The next step should be for us to confront our own lack of political freedom. In the political systems as they exist, we have no opportunity of effectively influencing the conduct of wars waged in our name.”

How to sound as if you've read it:

War photography - what is it good for? Making us feel bad about ourselves and despairing of humanity.

 

The Ongoing Moment by Geoff Dyer (2005), digested by Rachel Segal Hamilton

This is not a history book. True, it covers the work and lives of some of the biggest figures (mainly American) in photography – including Alfred Steiglitz, Walker Evans, Dorothea Lange, Diane Arbus, William Eggleston and Nan Goldin. But instead of progressing chronologically as one might expect, the structure is playful, grouping together pictures shot by different photographers of the same subjects: blind people, subways, signs, hands, backs, hats, stairs, fences, snow, windows, roads, cinemas, clouds, petrol stations, barber shops, doors.

Mixed in with the close readings of photographs are musings on life, quotes from writers – such as Wordsworth, Italo Calvino, Jean Rhys – as well as photographers, and colourful biographical anecdotes. We learn about the resentment felt by André Kertész at having to take photographs for money while his personal work went unappreciated, about the time Richard Avedon photographed Jorge Luis Borges and about the intricacies of relationships between Alfred Steiglitz and Georgia O'Keefe.

From the outset Dyer positions himself as a non-expert – he doesn't even own a camera, apparently – and rather than making big theoretical claims about photography as a medium, he writes about how specific photographs have affected him emotionally. Skipping backwards and forwards through time, making connections between photographers and writers, images and ideas, The Ongoing Moment celebrates a personal approach to looking at photographs that reflects the hotchpotch way we understand the world.

In his own words:

“Photographers sometimes take pictures of each other; occasionally they take photographs – or versions – of each other's work. Consciously or not they are constantly in dialogue with their contemporaries and predecessors.”

“...there is, I am beginning to suspect, a strange rule in photography, namely that we never see the last of anyone or anything. They disappear or die and then, years later, they reappear, are reincarnated, in another lens.”

“My favourite photographs by Brassai are the ones done in daylight, especially the ones that look like they were done by Lartigue. It's quite possible that some of my favourite Shores were taken by Eggleston, and vice versa. Perhaps it's not such a surprise, then, that my favourite Walker Evans (WE) photograph was taken by Edward Weston (EW).”

How to sound as if you've read it:

You know, the development of photography has been much more like a conversation than a story.

 

After Photography by Fred Ritchn (2009), digested by Diane Smyth

It takes a brave author to tackle digital media, a medium changing so fast that any attempt to read it looks outdated before the ink is dry. And yet that’s what Fred Ritchin did in After Photography, attempting to describe what’s new about digital photography and how it’s changed us.

As the title suggests, Ritchin believes digital photography is a fundamental shift rather than a simple change of tools, and he backs up his argument by considering both its ubiquity and its malleability. Digital photography started when National Geographic modified a horizontal photograph of the pyramids to create a more aesthetically pleasing front cover, Ritchin argues, shaking our belief in the image as proof.

The fact that we are all now armed with digital cameras, especially those embedded in our smartphones, means that we are all looking at the world second-hand via images, and also constantly presenting ourselves for image-based consumption.

It’s a gloomy reading of a brave new world, but Ritchin also suggests new strategies – a shift into “an interactive, networked multimedia”, in which hotspots link into other images and more information. Ritchin’s references to YouTube and MySpace already feel outdated, and his thoughts on surveillance seem tentative now that Wikileaks has blown the lid off the NSA program but it’s a game attempt to draw a line in the sand.

In his own words

"Photography in the digital environment involves the reconfiguration of the image into a mosaic of millions of changeable pixels, not a continuous tone imprint of a visible reality. Rather than a quote from appearances, it serves as an initial recording, a preliminary script, which may precede a quick and easy reshuffling."

"The multitudes of photographers now intensely staring not at the surrounding world, nor at their loved ones being wed or graduating, but at their camera backs or cellphones searching for an image on the small screens, or summoning the past as an archival image on these same screens, is symptomatic of the image’s primacy over the existence it is supposed to depict."

"Even before the ubiquity of a billon cell phone cameras, we were already in rehearsal for the pose, the look and a diminished sense of privacy."

How to sound as if you've read it

The web is all around us; the only solution is to go further into it.

Camera Lucida: Reflections on Photography by Roland Barthes (1980), digested by Tim Clark

Camera Lucida is a short, personal response to photography, so it's strange that it has achieved canonical status, but the magnetism it exerts extends to artists and writers alike. This book is a reflection on longing and loss written after Barthes' mother died. It's curious and affecting, exploring the relationship between photography, history and death.

Barthes explains two key concepts that can be applied when looking at photographs. The first he calls the studium – vague details which constitute the photograph’s subject, meaning and context.

However it's the second concept, the punctum, that has really resonated. By this he means the aspect of an image that attracts the viewer, something intensely private, unexpected and thus indelible. “A photograph’s punctum is that accident which pricks me (but also bruises me, is poignant to me)” he wrote. The discussion centres on a photograph from 1898, an image of his mother when she was a child, never at any point shown in the book. “For you, it would be nothing but an indifferent picture, one of the thousand manifestations of the ‘ordinary’”.

So subjective, and at times sentimental, is his examination of photography that initial responses to the book were scathing. Conversely, perhaps it is this very act of personalisation and the sense of vulnerability that has continued to capture imaginations in the 30 years since publication. Indeed, the academic Geoffrey Batchen, in his book Photography Degree Zero ventures that Camera Lucida is perhaps the most popular and influential contribution to photography to this day.

In his own words

“Photography: it reminds us of its mythic heritage only by that faint uneasiness which seizes me when I look at ‘myself’ on a piece of paper.”

“Ultimately, Photography is subversive not when it frightens, repels or even stigmatises, but when it is pensive, when it thinks.”

“Not only is the Photograph never, in essence, a memory, but it actually blocks memory, quickly becomes a counter-memory.”

How to sound as if you've read it

All photography tells us death in the future.

Lewis Bush is a photographer and writer. He contributes to a range of sites and publications. Follow him on Twitter @lewiskaybush

Diane Smyth is deputy editor of the British Journal of Photography and has also written for Foam, Aperture, Creative Review, The Times, The Guardian, Philosophy of Photography and Photomonitor

Rachel Segal Hamilton writes about photography for the British Journal of Photography, Photomonitor and IdeasTap, where she works as Commissioning Editor. Follow her on twitter @rachsh

Tim Clark is the Editor in Chief and Director of 1000 Words Photography Magazine. Follow him on Twiter @1000wordsmag

转载于:https://www.cnblogs.com/hashbang/p/6265774.html

D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:28:8 java: 类 MemberController 是公共的, 应在名为 MemberController.java 的文件中声明 D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:4:29 java: 找不到符号 符号: 类 FriendshipStatus 位置: 程序包 com.photography.model D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:7:31 java: 找不到符号 符号: 类 BlogService 位置: 程序包 com.photography.service D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:8:31 java: 找不到符号 符号: 类 FriendshipService 位置: 程序包 com.photography.service D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:9:31 java: 找不到符号 符号: 类 UserService 位置: 程序包 com.photography.service D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:30:19 java: 找不到符号 符号: 类 BlogService 位置:com.photography.controller.MemberController D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:31:19 java: 找不到符号 符号: 类 UserService 位置:com.photography.controller.MemberController D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:32:19 java: 找不到符号 符号: 类 FriendshipService 位置:com.photography.controller.MemberController D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:34:29 java: 找不到符号 符号: 类 BlogService 位置:com.photography.controller.MemberController D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:35:29 java: 找不到符号 符号: 类 UserService 位置:com.photography.controller.MemberController D:\BaiduNetdiskDownload\PhotoClubSystem\src\main\java\com\photography\controller\ManagerController.java:36:29 java: 找不到符号 符号: 类 FriendshipService 位置:com.photography.controller.MemberController
最新发布
06-24
<think>我们遇到了多个编译错误,主要涉及两个方面:1.类命名与文件名不匹配:`ManagerController.java`文件中声明了一个公共类`MemberController`,这会导致编译错误,因为公共类必须与文件名一致。2.缺少相关的类:如`FriendshipStatus`、`BlogService`、`FriendshipService`、`UserService`等。解决方案:1.对于第一个问题,我们需要将类名改为`ManagerController`或者将文件名改为`MemberController.java`。根据项目结构,这里应该是`ManagerController`,所以我们将类名改为`ManagerController`。2.对于第二个问题,我们需要创建缺失的类(如果尚未创建)或者检查包路径是否正确。假设缺失的类尚未创建,我们将创建以下类:-`com.photography.model.FriendshipStatus`:这是一个枚举,表示好友关系的状态。-`com.photography.service.BlogService`:博客服务接口。-`com.photography.service.FriendshipService`:好友关系服务接口。-`com.photography.service.UserService`:用户服务接口。下面我们将逐步解决这些问题。步骤1:重命名类(在ManagerController.java文件中)将类`MemberController`改为`ManagerController`。步骤2:创建缺失的类。首先,创建枚举`FriendshipStatus`:```javapackagecom.photography.model;publicenumFriendshipStatus{PENDING,//等待接受ACCEPTED,//已接受REJECTED,//已拒绝BLOCKED//已屏蔽}```然后,创建服务接口(先创建接口,具体实现稍后):BlogService.java:```javapackagecom.photography.service;importcom.photography.model.Blog;publicinterfaceBlogService{//定义博客相关的方法}```FriendshipService.java:```javapackagecom.photography.service;importcom.photography.model.Friendship;importcom.photography.model.FriendshipStatus;publicinterfaceFriendshipService{//更新好友请求状态voidupdateFriendshipStatus(LongfriendshipId,FriendshipStatusstatus);}```UserService.java:```javapackagecom.photography.service;importcom.photography.model.User;publicinterfaceUserService{//根据用户名查找用户UserfindByUsername(Stringusername);}```步骤3:修改`ManagerController`类,确保注入的服务使用正确的类型。修改后的ManagerController.java文件内容如下:```javapackagecom.photography.controller;importcom.photography.model.FriendshipStatus;importcom.photography.service.BlogService;importcom.photography.service.FriendshipService;importcom.photography.service.UserService;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.*;@Controller@RequestMapping("/manager")publicclassManagerController{privatefinalBlogServiceblogService;privatefinalUserServiceuserService;privatefinalFriendshipServicefriendshipService;//使用构造器注入publicManagerController(BlogServiceblogService,UserServiceuserService,FriendshipServicefriendshipService){this.blogService=blogService;this.userService=userService;this.friendshipService=friendshipService;}//示例:处理更新好友请求状态@PostMapping("/friendships/{friendshipId}/status")publicStringupdateFriendshipStatus(@PathVariableLongfriendshipId,@RequestParamFriendshipStatusstatus){friendshipService.updateFriendshipStatus(friendshipId,status);return"redirect:/manager/friendships";}//其他管理方法...}```注意:以上代码假设我们已经有了`Blog`、`Friendship`、`User`等模型类。如果还没有,需要创建这些模型类。步骤4:如果服务接口的实现类尚未创建,我们需要创建它们,并使用`@Service`注解标记,以便Spring能够注入。例如,`BlogServiceImpl`:```javapackagecom.photography.service.impl;importcom.photography.service.BlogService;importorg.springframework.stereotype.Service;@ServicepublicclassBlogServiceImplimplementsBlogService{//实现方法}```同样,创建`UserServiceImpl`和`FriendshipServiceImpl`。完成以上步骤后,重新编译项目,这些错误应该得到解决。但是,请注意,错误信息中还提到`ManagerController.java`的第28行是`publicclassMemberController`,所以我们必须确保类名已改为`ManagerController`。如果问题仍然存在,请检查包路径和导入语句是否正确。如果项目中有其他错误,请根据具体的错误信息继续解决。</think>### 编译错误分析与解决方案 #### 错误分析 根据您提供的错误信息,主要存在两类问题: 1. **文件名与类名不匹配**:`ManagerController.java` 文件中声明了 `public class MemberController` 2. **缺少依赖类和接口**:项目缺少 `FriendshipStatus`, `BlogService`, `FriendshipService`, `UserService` 等类 #### 解决方案 ### 1. 修复文件名与类名不匹配问题 **修改 `ManagerController.java` 文件:** ```java // ManagerController.java package com.photography.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/manager") public class ManagerController { // 类名改为 ManagerController private final BlogService blogService; private final UserService userService; private final FriendshipService friendshipService; public ManagerController(BlogService blogService, UserService userService, FriendshipService friendshipService) { this.blogService = blogService; this.userService = userService; this.friendshipService = friendshipService; } // 管理端方法实现... } ``` ### 2. 创建缺失的模型和服务类 #### 模型类:`FriendshipStatus.java` ```java // src/main/java/com/photography/model/FriendshipStatus.java package com.photography.model; public enum FriendshipStatus { PENDING, // 等待接受 ACCEPTED, // 已接受 REJECTED, // 已拒绝 BLOCKED // 已屏蔽 } ``` #### 服务接口:`BlogService.java` ```java // src/main/java/com/photography/service/BlogService.java package com.photography.service; import com.photography.model.Blog; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; public interface BlogService { Blog saveBlog(Blog blog); Optional<Blog> getBlogById(Long id); Page<Blog> getAllBlogs(Pageable pageable); void deleteBlog(Long id); Page<Blog> getBlogsByUserId(Long userId, Pageable pageable); } ``` #### 服务接口:`FriendshipService.java` ```java // src/main/java/com/photography/service/FriendshipService.java package com.photography.service; import com.photography.model.Friendship; import com.photography.model.FriendshipStatus; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; public interface FriendshipService { Friendship sendFriendRequest(Long senderId, Long receiverId); void updateFriendshipStatus(Long friendshipId, FriendshipStatus status); Page<Friendship> getPendingRequests(Long userId, Pageable pageable); Page<Friendship> getFriends(Long userId, Pageable pageable); boolean isFriends(Long user1Id, Long user2Id); } ``` #### 服务接口:`UserService.java` ```java // src/main/java/com/photography/service/UserService.java package com.phptography.service; import com.photography.model.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; public interface UserService { User saveUser(User user); Optional<User> getUserById(Long id); Optional<User> getUserByEmail(String email); Optional<User> getUserByUsername(String username); Page<User> getAllUsers(Pageable pageable); void deleteUser(Long id); User updateUserProfile(Long userId, User updatedUser); } ``` ### 3. 创建基础模型类 #### `User.java` 模型 ```java // src/main/java/com/photography/model/User.java package com.photography.model; import jakarta.persistence.*; import lombok.Data; import java.time.LocalDateTime; @Entity @Data public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true, nullable = false) private String username; @Column(unique = true, nullable = false) private String email; private String password; private String realName; private String bio; private String location; private String profilePic; private String website; private LocalDateTime createdAt = LocalDateTime.now(); // 社交媒体账号 private String socialWeibo; private String socialInstagram; private String social500px; // 隐私设置 private boolean showLocation = true; private boolean showEquipment = true; private boolean receiveNewsletter = true; // 角色和权限 private String role = "USER"; } ``` #### `Friendship.java` 模型 ```java // src/main/java/com/photography/model/Friendship.java package com.photography.model; import jakarta.persistence.*; import lombok.Data; import java.time.LocalDateTime; @Entity @Data public class Friendship { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne @JoinColumn(name = "sender_id", nullable = false) private User sender; @ManyToOne @JoinColumn(name = "receiver_id", nullable = false) private User receiver; @Enumerated(EnumType.STRING) private FriendshipStatus status = FriendshipStatus.PENDING; private LocalDateTime createdAt = LocalDateTime.now(); private LocalDateTime updatedAt; } ``` #### `Blog.java` 模型 ```java // src/main/java/com/photography/model/Blog.java package com.photography.model; import jakarta.persistence.*; import lombok.Data; import java.time.LocalDateTime; import java.util.List; @Entity @Data public class Blog { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String description; @Lob private String content; // HTML内容 @ManyToOne @JoinColumn(name = "user_id", nullable = false) private User author; private String coverImage; @ElementCollection private List<String> tags; @Enumerated(EnumType.STRING) private BlogStatus status = BlogStatus.PUBLISHED; private LocalDateTime createdAt = LocalDateTime.now(); private LocalDateTime updatedAt; public enum BlogStatus { DRAFT, PUBLISHED, ARCHIVED } } ``` ### 4. 实现服务类 #### `BlogServiceImpl.java` ```java // src/main/java/com/photography/service/impl/BlogServiceImpl.java package com.photography.service.impl; import com.photography.model.Blog; import com.photography.repository.BlogRepository; import com.photography.service.BlogService; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class BlogServiceImpl implements BlogService { private final BlogRepository blogRepository; public BlogServiceImpl(BlogRepository blogRepository) { this.blogRepository = blogRepository; } @Override public Blog saveBlog(Blog blog) { return blogRepository.save(blog); } @Override public Optional<Blog> getBlogById(Long id) { return blogRepository.findById(id); } @Override public Page<Blog> getAllBlogs(Pageable pageable) { return blogRepository.findAll(pageable); } @Override public void deleteBlog(Long id) { blogRepository.deleteById(id); } @Override public Page<Blog> getBlogsByUserId(Long userId, Pageable pageable) { return blogRepository.findByAuthorId(userId, pageable); } } ``` #### `UserServiceImpl.java` ```java // src/main/java/com/photography/service/impl/UserServiceImpl.java package com.photography.service.impl; import com.photography.model.User; import com.photography.repository.UserRepository; import com.photography.service.UserService; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } @Override public User saveUser(User user) { if (user.getPassword() != null) { user.setPassword(passwordEncoder.encode(user.getPassword())); } return userRepository.save(user); } @Override public Optional<User> getUserById(Long id) { return userRepository.findById(id); } @Override public Optional<User> getUserByEmail(String email) { return userRepository.findByEmail(email); } @Override public Optional<User> getUserByUsername(String username) { return userRepository.findByUsername(username); } @Override public User updateUserProfile(Long userId, User updatedUser) { return userRepository.findById(userId) .map(user -> { user.setRealName(updatedUser.getRealName()); user.setBio(updatedUser.getBio()); user.setLocation(updatedUser.getLocation()); user.setWebsite(updatedUser.getWebsite()); // 更新其他字段... return userRepository.save(user); }) .orElseThrow(() -> new RuntimeException("User not found")); } } ``` ### 5. 创建 JPA 仓库接口 #### `BlogRepository.java` ```java // src/main/java/com/photography/repository/BlogRepository.java package com.photography.repository; import com.photography.model.Blog; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; public interface BlogRepository extends JpaRepository<Blog, Long> { Page<Blog> findByAuthorId(Long userId, Pageable pageable); } ``` #### `UserRepository.java` ```java // src/main/java/com/photography/repository/UserRepository.java package com.photography.repository; import com.photography.model.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByUsername(String username); Optional<User> findByEmail(String email); boolean existsByUsername(String username); boolean existsByEmail(String email); } ``` ### 6. 修复控制器依赖注入 在 `ManagerController` 中正确注入服务: ```java // ManagerController.java 更新后 package com.photography.controller; import com.photography.model.FriendshipStatus; import com.photography.service.BlogService; import com.photography.service.FriendshipService; import com.photography.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/manager") public class ManagerController { private final BlogService blogService; private final UserService userService; private final FriendshipService friendshipService; public ManagerController(BlogService blogService, UserService userService, FriendshipService friendshipService) { this.blogService = blogService; this.userService = userService; this.friendshipService = friendshipService; } @PostMapping("/friendships/{friendshipId}/status") public String updateFriendshipStatus(@PathVariable Long friendshipId, @RequestParam FriendshipStatus status) { friendshipService.updateFriendshipStatus(friendshipId, status); return "redirect:/manager/friendships"; } // 其他管理端点... } ``` ### 项目结构验证 修复后项目应具有以下结构: ``` src/main/java/com/photography/ ├── controller/ │ ├── ManagerController.java │ ├── MemberController.java │ └── AuthController.java ├── model/ │ ├── User.java │ ├── Blog.java │ ├── Friendship.java │ └── FriendshipStatus.java ├── repository/ │ ├── UserRepository.java │ ├── BlogRepository.java │ └── FriendshipRepository.java ├── service/ │ ├── BlogService.java │ ├── UserService.java │ ├── FriendshipService.java │ └── impl/ │ ├── BlogServiceImpl.java │ ├── UserServiceImpl.java │ └── FriendshipServiceImpl.java └── PhotographyApplication.java ``` ### 关键修复点总结 1. **命名一致性**: - 确保文件名与公共类名完全匹配 - 使用符合Java规范的驼峰命名法 2. **依赖注入**: - 使用构造器注入替代字段注入 - 明确服务接口和实现的关系 3. **分层架构**: - 清晰的controller-service-repository分层 - 模型与持久化分离 4. **类型安全**: - 使用枚举替代字符串常量 - 强类型参数传递 5. **异常处理**: - 在服务层处理业务异常 - 返回有意义的错误信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值